ak85
ak85

Reputation: 4264

jquery reorder li on click

I have the below jquery which prepends the clicked menu item to the top of the unordered list.

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

$('li').on('click', function() {
    $(this).parent().prepend(this);
});

What I want to have happen instead of moving it to the top of the list I want to place it after the next item I click on in the list. For example if I click on 2 then 3 the list item with the value of 2 would move after 3 in the list so the html would look like this.

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

I have attempted to do this with the below jQuery see fiddle, this works the first time I click on 2 then 3 but it doesn't work if you continue to click. How can this be achieved?

$('li').on('click', function() {
    var test = this;
    console.log($(this).text());
    $('li').on('click', function() {
        $(this).after(test);
    });
    //$(this).parent().prepend(this);
});

Upvotes: 2

Views: 3161

Answers (4)

Mr. Alien
Mr. Alien

Reputation: 157424

Use .before() and .after() with .next() and .prev()

$('ul li span:nth-of-type(1)').on('click', function() {
    $(this).parent().prev().before($(this).parent());
});

$('ul li span:nth-of-type(2)').on('click', function() {
    $(this).parent().next().after($(this).parent());
});

Demo

So, here we go with the explanation, here am selecting the first span using nth- selectors and than onclick, we move the parent of the span i.e li before the previous li and the second one is the opposite of the same.

Can shorten up the above code by caching up the element like

$('ul li span:nth-of-type(1)').on('click', function() {
    moveup =  $(this).parent();
    moveup.prev().before(moveup);
});

$('ul li span:nth-of-type(2)').on('click', function() {
    movedown =  $(this).parent();
    movedown.next().after(movedown);
});

Demo 2

Upvotes: 1

mohamedrias
mohamedrias

Reputation: 18576

$('ul li').on('click', function() {
    $(this).next().after($(this));
});

This will help you change the order as well

Upvotes: 0

Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

try this ..its working...

 $('li').on('click', function() {
        var test = this;
        $(this).next("li").after(test);
    });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

I think, what you might need is to store the first click element and then use it in the second click like below

jQuery(function(){
    var item;
    $('li').on('click', function () {
        if (item) {
            $(this).after(item)
            item = undefined;
        } else {
            item = this;
        }
    });
})

Demo: Fiddle

Upvotes: 2

Related Questions