Search code examples
javascripthtmlslideshow

Javascript code for automatic slideshow is not working in seperate .js file but it is working inside html


I am trying to use javascript to make an automatic slideshow. I am new to javascripts . I have got this script from w3school . This script works if i use it inside my html code. But it doesnt work if i use a separate file for script . Basically i have alot of pages that uses the slideshow . I dont want to copy and paste this code again again to different html pages.

Here is a code of my HTML PAGE

I have linked the js file to the html (FILE DIRECTORY IS NOT AN ISSUE, i know its attached correctly. ). Kindly give me a direction to follow here

<script type="text/javascript" src="./scripts/main-script.js"></script>



    <div class="slideshow" id="main-div">
        <img class = "slide fade" src="./images/clean.JPG" alt="Cleaning">
        <img class = "slide fade" src="./images/about.jpg" >
        <img class = "slide fade" src="./images/greenclean.jpg">


        <button class="btn" onclick="location.href='contact.html'"> BOOK A CLEANING</button> <!-- adding button on image --> 
        <div class="text-block" >  CALL NOW 1844-562-5200 </div>


    </div>



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

        function carousel() {
            var i;
            var x = document.getElementsByClassName("slide");
            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, 8000); // Change image every 2 seconds
        }
    </script>  

Solution

  • Just add defer in the script tag in the header. Like so:

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

    I tried your code with defer and it worked.

    You see, without defer what happens is the javascript file is loaded before the images and the rest of the html body elements. Thus, the javascript code tries to get a reference to the image tags, it finds nothing. Because they were not loaded yet. That is why you use defer it tells the browser to load the rest of the HTML document before the javascript code

    Here is a link explaining it more (scroll down to the part about defer):

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

    Alternatively you can add the script tags at the end of the body element. Thus forcing the browser to load the script at the end.

    Check out Mozilla Developer Network's tutorials on javascript if you want more.

    Here's a link: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps