---
title: "Simplest jQuery slideshow code explanation"
description:
  "Building slideshow using jQuery could take a bit of code.  This is probably
  the simplest jQuery slideshow code you would see in action."
canonical_url: "https://www.bigbinary.com/blog/simplest-jquery-slideshow-code-explanation"
markdown_url: "https://www.bigbinary.com/blog/simplest-jquery-slideshow-code-explanation.md"
---

# Simplest jQuery slideshow code explanation

Building slideshow using jQuery could take a bit of code. This is probably the
simplest jQuery slideshow code you would see in action.

- Author: Neeraj Singh
- Published: February 18, 2010
- Categories: jQuery

[Jonathan Snook](http://snook.ca) wrote a blog titled
[Simplest jQuery SlideShow](http://snook.ca/archives/javascript/simplest-jquery-slideshow).
Checkout the [demo page](http://snook.ca/technical/fade/fade.html). 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.

```javascript
$(function () {
  $(".fadein img:gt(0)").hide();
  setInterval(function () {
    $(".fadein :first-child")
      .fadeOut()
      .next("img")
      .fadeIn()
      .end()
      .appendTo(".fadein");
  }, 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.

```html
<div id="container">
  <div class="lab">This is div1</div>
  <div class="lab">This is div2</div>
</div>
```

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

```javascript
$(".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.

```plaintext
Image1
Image2
Image3
```

After the code is executed the order becomes this.

```plaintext
Image2
Image3
Image1
```

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

```plaintext
Image3
Image1
Image2
```

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

```plaintext
Image1
Image2
Image3
```

And this cycle continues forever.

## Links

- [Human page](https://www.bigbinary.com/blog/simplest-jquery-slideshow-code-explanation)
