Back to Blog

Simplest jQuery slideshow code explanation

on February 18, 2010

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);

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>

Open this page in browser and execute following command in firebug.


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.


After the code is executed the order becomes this.


After the code is executed again then the order becomes this.


After the code is executed again then the order becomes this.


And this cycle continues forever.

You might also like

If you liked this blog post, check out similar ones from BigBinary