Liam Emery Liam Emery - 3 months ago 9
HTML Question

Why doesn't my .js file appear to do anything to my .html file?

I'm trying to create a basic image slider that just automatically slides through any given amount of images placed inside a div.

HTML

<head>
<script type="text/javascript" src="slider.js"></script>
</head>

<div class="images">
<img class="slides" src="img01.jpg">
<img class="slides" src="img02.jpg">
<img class="slides" src="img03.jpg">
<img class="slides" src="img04.jpg">
</div>


JavaScript

var myIndex = 0;
carousel();

function carousel() {
var i;
var x = document.getElementsByClassName("slides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 2000); // Change image every 2 seconds
}


But at the moment, it seems that this code isn't doing anything at all, this is the current output of the page.
enter image description here

So as you can see, the images are just being stacked on top of one and another instead of being played as a slideshow.

Answer

You're loading your script before the HTML is rendered, so when it tries to getElementsByClassName, there's nothing for it to find. Try moving to to below your HTML. And as a in a comment above, you're calling your function carousel() before you define it. Move that line to below the function definition.

Additionally, you can use

<script>
    document.addEventListener("DOMContentLoaded", function(event) {
        // all of your JavaScript goes here
    });
</script>

This will only load your JavaScript after the HTML is loaded and you can leave it in the head.

Comments