Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 72388

Why does javascript code not work when it is called from a different file? [closed]

$
0
0

I've used the following code in my website and it works.

<script>
    var myIndex = 0;
    carousel();

    function carousel() {
      var i;
      var x = document.getElementsByClassName("mySlides");
      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
    }
</script>

When I tried to put the same code in a file called main.js in a folder called js and wrote

<script src="js/main.js"></script>

where the code initially was, it didn't work. What have I done wrong?

My console errors read:

6 ERROR: 'document' is not defined. [no-undef] var x = document.getElementsByClassName("mySlides");

13 ERROR: 'setTimeout' is not defined. [no-undef] setTimeout(carousel, 10000); // Change image every 2 seconds


Viewing all articles
Browse latest Browse all 72388

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>