0

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>  
  • Possible duplicate of [How do I call a JavaScript function on page load?](https://stackoverflow.com/questions/3842614/how-do-i-call-a-javascript-function-on-page-load) – mickmackusa Sep 05 '18 at 08:36

5 Answers5

2

The script in the HTML is placed after your target HTML elements. Therefore, when the script in the HTML is called, your target HTML elements are ready. In contrast, when you link to a separate script file in head, your target HTML elements are not loaded yet when your script run.

Solution: Instead of calling carousel(); directly within <script>, call it in <body onload="carousel();">

Ricky Mo
  • 6,285
  • 1
  • 14
  • 30
0

it will be your file directory link

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

its hard to tell exactly what is the issue as i dont know your file directory layout i do my js tags as follow

`<script src="javaScript/home.js"></script>`

my main folder is named websiteName, inside of that i have all of my html files and sub folders for different things. i dont personally put my html files in a seperate file as makes access more complicated.

and place script files at the bottom of the page

a.c
  • 1
  • 1
  • I know my javascript file is attached, I used the alert () funtion to check if it is working . This function works but the rest of the code doesnt – Waleed Bashir Sep 05 '18 at 01:40
0

You've called the setTimeout inside the function, and of course it would not work, here is answer:

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

or you can use callbacks like this :

setTimeout(function(){
 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";
},8000);
Ahmad Reza
  • 26
  • 1
  • 5
  • https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_rr This code is taken from here and its working properly inside the html. When i use this code in a seperate script file it doesnt work – Waleed Bashir Sep 05 '18 at 01:54
  • have you tried my solutions?, btw why did you place button and div inside of slideshow class? – Ahmad Reza Sep 05 '18 at 01:56
  • I have tried setting timeout function outside the function but it doesnt work – Waleed Bashir Sep 05 '18 at 01:57
  • alternatively you can try using setInterval instead of setTimeout – Ahmad Reza Sep 05 '18 at 02:01
  • *"You've called the setTimeout inside the function, and of course it would not work"* - There's absolutely nothing wrong with calling `setTimeout` inside the function, that's how you get it to be repeat indefinitely (as an alternative to `setInterval()`). The way your answer suggests, it would only run once after 8 seconds and never again. Furthermore, in your first example you're not passing the function to `setTimeout` but actually invoking it, so it will only run once immediately and `setTimeout()` has no effect at all. – Lennholm Sep 05 '18 at 15:21
0

1.You did not have shown your css file though js script has been using css property.Did you mention these property in your css file?

/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
 animation-name: fade;
animation-duration: 1.5s;
}

@-webkit-keyframes fade {
from {opacity: .4} 
to {opacity: 1}
}

@keyframes fade {
from {opacity: .4} 
to {opacity: 1}
}

2.You can also use console of debugging tool of browser which help to show what is happening behind.

0

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

  • Oh great. Didn't know about this one . Its working fine now – Waleed Bashir Sep 05 '18 at 02:01
  • Good, also Ricky Mo's answer was correct, try it if you want. I would also recommend that you look into the differences between using defer and putting the script tag at the end of the body element. They both have their strengths and weaknesses. – Mohammad Abouchama Sep 05 '18 at 02:04
  • Yes i applied that method . seems like both do the same thing The external script deferred by the defer attribute is executed before the (DOMContentLoaded) is fired, i.e. when the initial HTML document has been completely loaded and parsed. The onLoad attribute on a tag, on the other hand, fires only when a web page is fully loaded – Waleed Bashir Sep 05 '18 at 02:11