The use of x.length

Code in Image:

The Code in Text Form:

        <img class="mySlides" src="mosque.jpg" style="width:100%">
        <img class="mySlides" src="img_band_ny.jpg" style="width:100%">
        <img class="mySlides" src="img_band_chicago.jpg" style="width:100%">

        // Automatic Slideshow - change image every 3 seconds
        var myIndex = 0;

        function carousel() 
        var i;
        var x = document.getElementsByClassName("mySlides");
        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, 3000);

Greetings everyone, currently I am learning to create a website and was planning to do a slideshow at the website. I found the tutorial at W3school (Link: I have problem in understand the the code state above. To be specific the x.length. May I ask what does the x.length do in this example? Does it same with length function which are used in counting the number of character in the string? But in this example I only have image, so what does the length are for ?

It’s checking if you’ve advanced beyond the last slide of the carousel. If you have, it resets the index back to the start.

1 Like

Ohhh okay, may I ask what will the value of x.length will be one the first run ? Sorry i am still kinda blur on how is the x.length work in this example :sweat_smile:

Well x is a collection of your slides.

        var x = document.getElementsByClassName("mySlides");

x.length will always be the total number of slides that you have.

“length” is not a dimension of something (like feet or mm). In this case it is the quantity of something.

So x.length is the qty of x, where x is listing the number of slides.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.