4

I have a list:

<li>item one<img src="/assets/img/site/up_arrow.png" class="upArrow"/><img src="/assets/img/site/down_arrow.png" class="downArrow"/</li>
<li>item two<img src="/assets/img/site/up_arrow.png" class="upArrow"/><img src="/assets/img/site/down_arrow.png" class="downArrow"/</li>
<li>item three<img src="/assets/img/site/up_arrow.png" class="upArrow"/><img src="/assets/img/site/down_arrow.png" class="downArrow"/</li>
<li>item four<img src="/assets/img/site/up_arrow.png" class="upArrow"/><img src="/assets/img/site/down_arrow.png" class="downArrow"/</li>
<li>item five<img src="/assets/img/site/up_arrow.png" class="upArrow"/><img src="/assets/img/site/down_arrow.png" class="downArrow"/</li>

Each one has an up and down arrow on. In my jquery I have:

$(".upArrow").click(function() {

});

$(".downArrow").click(function() {

});

How can I get it so that when a user clicks up arrow it swaps the li with the one above, and when they click down it swaps with the li below (if one exists).

0

3 Answers 3

6

jsFiddle( http://jsfiddle.net/A9j3E/6/ )

$(".upArrow").click(function() {
    $(this).parent().insertBefore( $(this).parent().prev() );
});

$(".downArrow").click(function() {
    $(this).parent().insertAfter( $(this).parent().next() );
});​
1
  • This is only for adjacent children, right? I mean if you want to swap first with 4th child, it won't work, I guess.
    – gsamaras
    Sep 26, 2015 at 18:18
1

You could get a reference to the list item, and insert it before/after its sibling.

$(".upArrow").on("click", function(){
  var li = $(this).closest("li");
  li.insertBefore( li.prev() );
});

Also, be sure to properly close your images. Your down arrow images were all malformed.

0

try something like this

$(".upArrow").click(function() {
  var thisItem = $(this).closest('li');
  var prevItem = thisItem.prev();

  if(prevItem.length != 0) {
    thisItem.before(prevItem);
  }
});

$(".downArrow").click(function() {
  var thisItem = $(this).closest('li');
  var nextItem = thisItem.next();

  if(nextItem.length != 0) {
    thisItem.after(nextItem);
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.