Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move list items?

Tags:

jquery

I have a normal unordered list

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

When I click on any of the list items it should appear 2nd in the list, if possible animate to second position.

I know an easy solution for this would to relatively position the UL and absolutely position the LIs and set the top position, but this not possible because of the way the markup is written.

like image 770
Lee Price Avatar asked Jan 03 '12 16:01

Lee Price


1 Answers

This does everything but the animation:

$('li').click(function() {
    var $this = $(this);
    $this.insertAfter($this.siblings(':eq(0)'));
});

When you click on a list item, it will insert it after the first item in the <ul>, i.e. the second position in the list.

Furthermore, you could animate this in various ways. Here's one:

$('li').click(function() {
    var $this = $(this),
        callback = function() {
            $this.insertAfter($this.siblings(':eq(0)'));
        };
    $this.slideUp(500, callback).slideDown(500);
});

Here's a working demo.

like image 126
FishBasketGordo Avatar answered Oct 19 '22 23:10

FishBasketGordo