panthro
panthro

Reputation: 24061

Swapping list elements with jQuery

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).

Upvotes: 4

Views: 4290

Answers (3)

Jonathan Payne
Jonathan Payne

Reputation: 2223

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

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

$(".downArrow").click(function() {
    $(this).parent().insertAfter( $(this).parent().next() );
});​

Upvotes: 6

nanobar
nanobar

Reputation: 66335

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);
  }
});

Upvotes: 0

Sampson
Sampson

Reputation: 268324

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.

Upvotes: 1

Related Questions