Can I use jQuery to easily move li elements up or down?
I have the following menu:
<ul id="menu" class="undecorated">
<li id="menuHome"><a href="/">Home</a> </li>
<li id="menuAbout"><a href="/Usergroup/About">About</a> </li>
<li id="menuArchives"><a href="/Usergroup/Archives">Archives</a> </li>
<li id="menuLinks"><a href="/Usergroup/Links">Links</a> </li>
</ul>
Is there an easy way to use jquery to reorder items? I imagine something like this:
$('#menuAbout').moveDown().moveDown()
But any other way to achieve this is appreciated.
+5
2 answers
This is actually not so difficult. JQuery almost gets you there using the "insertBefore" and "insertAfter" methods.
function moveUp($item) {
$before = $item.prev();
$item.insertBefore($before);
}
function moveDown($item) {
$after = $item.next();
$item.insertAfter($after);
}
You can use them as MoveDown ($ ('# menuAbout')); and the menuAbout element will move down.
If you want to extend jQuery to include these methods, you should write it like this:
$.fn.moveUp = function() {
before = $(this).prev();
$(this).insertBefore(before);
}
$.fn.moveDown = function() {
after = $(this).next();
$(this).insertAfter(after);
}
, $ ( "# MenuAbout" ) MoveDown();.
+22