Jonathan Snook wrote a blog titled Simplest jQuery SlideShow. Checkout the demo page. The full JavaScript code in its entirety is given below. If you understand this code then you don't need to read rest of the article.
1$(function () { 2 $(".fadein img:gt(0)").hide(); 3 setInterval(function () { 4 $(".fadein :first-child") 5 .fadeOut() 6 .next("img") 7 .fadeIn() 8 .end() 9 .appendTo(".fadein"); 10 }, 3000); 11});
appendTo removes and attaches elements
In order to understand what's going on above, I am constructing a simple test page. Here is the html markup.
1<div id="container"> 2 <div class="lab">This is div1</div> 3 <div class="lab">This is div2</div> 4</div>
Open this page in browser and execute following command in firebug.
1$(".lab:first").appendTo("#container");
Run the above command 5/6 times to see its effect. Every single time you run JavaScript the order is changing.
The order of div elements with class lab is changing because if a jQuery element is already part of document and that element is being added somewhere else then jQuery will do cut and paste and not copy and paste . Again elements that already exist in the document get plucked out of document and then they are inserted somewhere else in the document.
Back to the original problem
In the original code the very first image is being plucked out of document and that image is being added to set again. In simpler terms this is what is happening. Initially the order is like this.
1Image1 2Image2 3Image3
After the code is executed the order becomes this.
1Image2 2Image3 3Image1
After the code is executed again then the order becomes this.
1Image3 2Image1 3Image2
After the code is executed again then the order becomes this.
1Image1 2Image2 3Image3
And this cycle continues forever.