Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery arrange li order by clicking on a link

Need to change li position by clicking to move up or to move down.

<div>
  <ul>
    <li>Item1  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
    <li>Item2  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
    <li>Item3  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
    <li>Item4  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
    <li>Item5  <a class="moveUp">Move Up</a> <a class="moveDown">Move Down</a></li>
  </ul>
</div>

So what should happen here, for example, if we click Move up on Item2, the Item 2 will move up before Item 1.

I tryed to do like this, but it doesn't work:

$(".moveUp").click(function () {
    var thisLine = $(this).parent();
    var prevLine = thisLine.prev();
    prevLine.insertAfter(thisLine);
});

Hope some one can help me...

like image 766
user1309015 Avatar asked Apr 04 '12 15:04

user1309015


3 Answers

Try this:

$(".moveUp").click(function () {
    var thisLine = $(this).parent();
    var prevLine = thisLine.prev();
    prevLine.before(thisLine);
});

$(".moveDown").click(function () {
    var thisLine = $(this).parent();
    var prevLine = thisLine.next();
    prevLine.after(thisLine);
});

Working jsFiddle here.

like image 123
hohner Avatar answered Nov 13 '22 15:11

hohner


Try this.

$(".moveUp").click(function () {
    var $parent = $(this).parent();
    $parent.prev().before($parent);
});
$(".moveDown").click(function () {
    var $parent = $(this).parent();
    $parent.next().after($parent);
});

Working demo - http://jsfiddle.net/vQmHU/

like image 31
ShankarSangoli Avatar answered Nov 13 '22 14:11

ShankarSangoli


This should work and will also not move the element outside of the UL when you try and move it up at the top or down at the bottom:

$('.moveUp').click(function(){
    var liItem = $(this).parent();
    if (liItem.prev().is('li'))
    {
        liItem.insertBefore(liItem.prev())
    }
});

$('.moveDown').click(function(){
    var liItem = $(this).parent();
    if (liItem.next().is('li'))
    {
        liItem.insertAfter(liItem.next())
    }
});

Working Example: http://jsfiddle.net/BDecp/

Also, your code should be wrapped with this:

$(document).ready(function () {
    //Code Here
});
like image 2
JakeJ Avatar answered Nov 13 '22 13:11

JakeJ