Having trouble moving list items up and down
Posted: Mon Jul 19, 2010 9:03 am
Hi DevNetwork people!
I try to google my fingers off before I post here, but I think I'm doing this wrong.
My goal is to simply move list items up and down. I have a simple solution - use insertBefore(). However, this does not seem to be working in Webkit browsers (Android, Safari, Chrome, etc) or Firefox. Sometimes you have to click one of the buttons up to three times before the list item actually moves!
Here's my JavaScript:
and here's a relevant snippet of my HTML:
Am I doing something wrong here? I'd like to avoid using JQuery or other JavaScript library and just learn how to write the right code.
An example is attached.
Thanks!
I try to google my fingers off before I post here, but I think I'm doing this wrong.
My goal is to simply move list items up and down. I have a simple solution - use insertBefore(). However, this does not seem to be working in Webkit browsers (Android, Safari, Chrome, etc) or Firefox. Sometimes you have to click one of the buttons up to three times before the list item actually moves!
Here's my JavaScript:
Code: Select all
function shift(direction, id) {
var btn = document.getElementById(id);
if (direction == "up") {
var theParentNode = btn.parentNode;
var thePrevSibling = btn.previousSibling;
if (!thePrevSibling) {
alert("Can't go up any higher!");
return;
}
theParentNode.insertBefore(btn, thePrevSibling);
} else if (direction == "down") {
var theParentNode = btn.parentNode;
var theNextSibling = btn.nextSibling;
if (!theNextSibling) {
alert("Can't go down any lower!");
return;
}
theParentNode.insertBefore(theNextSibling, btn);
}
}Code: Select all
<ul>
<li>I'm a special little list item.</li>
<li id="exampleItem">
<strong>Shift me!</strong> 
<a class="shiftBtn" href="#" onclick="shift('up', 'exampleItem')">˄</a>
<a class="shiftBtn" href="#" onclick="shift('down', 'exampleItem')">˅</a>
</li>
<li>I'm a list item.</li>
<li>Another list item!</li>
</ul>An example is attached.
Thanks!