Liam Emery Liam Emery - 1 year ago 78
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.


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

<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">


var myIndex = 0;

function carousel() {
var i;
var x = document.getElementsByClassName("slides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
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 Source

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

    document.addEventListener("DOMContentLoaded", function(event) {
        // all of your JavaScript goes here

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download