Reputation: 1180
I am working on a list that changes position according to the button clicked.Here is a unordered list i had created and have contents like this
<ul>
<li>
<div>
<span> cat3_sub3</span>
<div style="text-align:right;float:right;">
[ <a href="#" class="up_sub" id="3_3">Up</a> ]
[ <a href="#" class="down_sub" id="3_3">Down</a> ]
</div>
</div>
</li>
<li>
<div>
<span> cat3_sub2</span>
<div style="text-align:right;float:right;">
[ <a href="#" class="up_sub" id="2_3">Up</a> ]
[ <a href="#" class="down_sub" id="2_3">Down</a> ]
</div>
</div>
</li>
<li>
<div>
<span> cat3_sub2</span>
<div style="text-align:right;float:right;">
[ <a href="#" class="up_sub" id="1_3">Up</a> ]
[ <a href="#" class="down_sub" id="1_3">Down</a> ]
</div>
</div>
</li>
</ul>
now i want to change the list up or down as teh up or down link is clicked. so for this i wrote a javascript like this
$(document).ready(function(){
$(".up_sub,.down_sub").click(function(){
var rank_id = this.id;
rank_id = rank_id.split("_");
var rank = (rank_id[0]);
var cat_id = rank_id[1];
var max_rank = get_max_rank(cat_id);
if ($(this).is(".up_sub")) {
if(rank!=max_rank){ //to not to move up than top most
var thisLine = $(this).parent();
var prevLine = thisLine.prev();
prevLine.before(thisLine);
}
}
});
});
but this didn't worked. i checked if it reaches inside the function using alert()
. it gave response. But the list are not changing their position. what is the reason behind this. and what should be done to change the list position?
Upvotes: 0
Views: 1323
Reputation: 388326
Try
$('.up_sub').click(function(){
var li = $(this).closest('li');
var prev = li.prev();
if(prev.length){
li.detach().insertBefore(prev);
}
});
$('.down_sub').click(function(){
var li = $(this).closest('li');
var next = li.next();
if(next.length){
li.detach().insertAfter(next);
}
});
Demo: Fiddle
Upvotes: 3