ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I found this automatic slideshow that I want to use but I can't quite understand what is it doing:
Code:
var slideIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
slideIndex++;
if (slideIndex > x.length) {slideIndex = 1}
x[slideIndex-1].style.display = "block";
setTimeout(carousel, 2000); // Change image every 2 seconds
}
I get a lot of it but some parts, like the "(i = 0; i < x.length; i++)" leave me stumped. Could somebody explain this to me? Thanks.
x.length is the length of x array, this array contains references to all elements that have .mySlides css classes in your html document
The loop sets css display property to none in each .mySlides css class
The array index starts at zero and ends at array.length -1, that's why i (= the array index) can't be greater than x.length
The loop initializes all display attributes (style.display) of the mySlides class to none. (ie. hidden).
Since the scope of slideIndex is outside the function, it keeps the old value. So you need to increment it separately from "i" which initializes.
As a further exercise, consider:
Having initially initialized all displays to none, you don't really need to reinitialize all in every call to the function. You could have a variable called as "j" which holds the value of slideIndex before incrementing. Then you might change the code as:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.