Reputation: 3233
I am trying to create a system where you can click back and forward to rearrange gallery images based up importance. My initial code below is to move the element backwards and seems to work ok initially. The problem arrises however if I try to move the element back more than once.
It seems to be that after the $('#'+current_position).remove().insertBefore($('#'+new_position));
the element becomes unresponsive.
<div class="card-body">
<div class="container-fluid">
<div class="row">
<div class="col-sm gallery-item" id="1">
One of three columns
<div class="options">
<div class="back">b</div>
<div class="forward">f</div>
</div>
</div>
<div class="col-sm gallery-item" id="2">
Two of three columns
<div class="options">
<div class="back">b</div>
<div class="forward">f</div>
</div>
</div>
<div class="col-sm gallery-item" id="3">
Three of three columns
<div class="options">
<div class="back">b</div>
<div class="forward">f</div>
</div>
</div>
</div>
</div>
</div>
<script>
$( ".back" ).click(function() {
var current_position = $(this).closest('.gallery-item').attr('id')
console.log(current_position)
if(current_position > 1){
var new_position = current_position - 1;
console.log(new_position)
$('#'+current_position).remove().insertBefore($('#'+new_position));
$('#'+new_position).attr("id",current_position);
$(this).closest('.gallery-item').attr("id",new_position);
}
});
</script>
Upvotes: 0
Views: 54
Reputation: 683
Switching the remove()
with detach()
will solve the problem.
$( ".back" ).click(function() {
var current_position = $(this).closest('.gallery-item').attr('id')
console.log(current_position)
if(current_position > 1){
var new_position = current_position - 1;
console.log(new_position)
$('#'+current_position).detach().insertBefore($('#'+new_position));
$('#'+new_position).attr("id",current_position);
$(this).closest('.gallery-item').attr("id",new_position);
}
});
Upvotes: 3
Reputation: 1973
The problem is remove()
deletes the element itself and all the elements inside, you can try to rebind de click event to the .back
class and should work.
But a more elegant solution:
$(".forward").click(function () {
var $parent = $(this).parents(".gallery-item");
$parent.insertAfter($parent.next());
});
$(".back").click(function () {
var $parent = $(this).parents(".gallery-item");
$parent.insertBefore($parent.prev());
});
Upvotes: 0