Rickstar
Rickstar

Reputation: 6189

move up/down in jquery

I Have 5 spans i am trying to move them up/down (swap positions) in jquery

<a href="#" id="up">Up!</a> 
<a href="#" id="down">Down!</a>

<span id='1'>Test1</span><br>
<span id='2'>Test2</span><br>
<span id='3'>Test3</span><br>
<span id='4'>Test4</span><br>
<span id='5'>Test5</span>

i have tryed but nothing is happening.

 $("#"+LinkID).insertBefore($("#"+LinkID).next('span')); 

Upvotes: 1

Views: 6449

Answers (3)

Brad Christie
Brad Christie

Reputation: 101604

That's because you're telling a span to go before the next span (i.e., stay the same). Try using insertBefore on a previous or insertAfter with a next.

EDIT Try this on for size: http://jsfiddle.net/eJk3R/

Upvotes: 4

mmurch
mmurch

Reputation: 463

Consider this example. Its not styled up well or anything, but clicking on Up or Down inserts that element either before its previous sibling or after its next sibling.

<style type="text/css">
    span.swapMe {
        float: left;
        clear: left;
    }
</style>

<span class="swapMe">Test1 <span class="up">Up!</span> <span class="down">Down!</span></span>
<span class="swapMe">Test2 <span class="up">Up!</span> <span class="down">Down!</span></span>
<span class="swapMe">Test3 <span class="up">Up!</span> <span class="down">Down!</span></span>
<span class="swapMe">Test4 <span class="up">Up!</span> <span class="down">Down!</span></span>
<span class="swapMe">Test5 <span class="up">Up!</span> <span class="down">Down!</span></span>


<script type="text/javascript">

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

$("span.down").click(function(){
    $(this).parent().insertAfter($(this).parent().next())
});


</script>

Upvotes: 0

Harmen
Harmen

Reputation: 22438

You're trying to insert a certain span before the next one, which makes it remain on the same position...

$("#"+LinkID).insertBefore($("#"+LinkID).prev());

or

$("#"+LinkID).insertAfter($("#"+LinkID).next()); 

would be better.

Upvotes: 3

Related Questions