0

This code works from <script> tag in HTML document but it doesn't work when called upon from external file. code:

<html>
<link rel='stylesheet' href='main.css'>
<script src="js/main.js"></script>
<body>
<div class="slideshow-container">

<div class="mySlides fade"> <img src="images/slide1.jpg" style="width:100%"></div>

<div class="mySlides fade"> <img src="images/slide2.jpg" style="width:100%"></div>

<div class="mySlides fade"> <img src="images/slide3.jpg" style="width:100%"></div>

<script>
var slideIndex = 0;
showSlides();

function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none"; 
}
slideIndex++;
if (slideIndex> slides.length) {slideIndex = 1} 
slides[slideIndex-1].style = "display:block"; 
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
</body>
</html>

When I put everything from the <script> tag into main.js it throws an error on this line:slides[slideIndex-1].style = "display:block"; Uncaught TypeError: Cannot set property 'style' of undefined at showSlides.

Any ideas as to why? Thanks!

Laurynas
  • 61
  • 3
  • It has nothing to do with you moving the JS from inside the script element to an external file. It is because when you did that you **also moved the script element itself** – Quentin Jan 19 '17 at 21:33
  • Strange. getElementById() never presented this problem. That's why I got lost. Thanks anyways - it works when I move the script reference down! – Laurynas Jan 19 '17 at 21:51

0 Answers0