JQuery sort order by clicking on the link

You must change the 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, item 2 will move up to item 1.

I tried to do this, but this will not work:

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

Hope someone can help me ...

+7
source share
5 answers

This should work and will not move the element outside of UL when you try to move it up or down below:

 $('.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/

In addition, your code should be wrapped as follows:

 $(document).ready(function () { //Code Here }); 
+2
source

Try the following:

 $(".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); }); 

JsFiddle work here .

+6
source

Try it.

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

+3
source

this one only reorders the list items:

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

http://jsfiddle.net/j7xtS/2/

 $('ul').on('click', 'a', function(){ var $this = $(this), $li = $this.parent(); if ($this.hasClass('moveUp') && $li.prev().length>0){ $li.prev().before($li[0]); } else if ($this.hasClass('moveDown') && $li.next().length>0){ $li.next().after($li[0]); } });​ 
0
source

All Articles