Search code examples
javascriptjquerydom-manipulationjquery-after

Why does jQuery .after() fire only once?


I'm trying to create a jQuery carousel that loops continuously. When the user selects "rotate," the first li is placed after the last li using the .after() method. This works the first time only. After that, the li's won't rearrange themselves. Here is my HTML:

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

<a href="#">Rotate</a>

And here is my JavaScript:

var list = $('ul'),
    firstItem = list.find('li:first'),
    lastItem = list.find('li:last');

$('a').on('click', function(){
    lastItem.after( firstItem );
});

Here's a fiddle: http://jsfiddle.net/brianeoneill/76BP8/

Thanks in advance!


Solution

  • Each time your code runs, it puts the same element (1) after the 3.

    If you want to keep re-arranging, you'll need to re-set the variables to :first and :last each time.