I have this code
<div id="main" style="background:#aaaaaa;float:left;height:160px;margin:5px;position:relative;display:block;width:630px;">
<div id="1" class="item" style="background:#ffaacc;float:left;width:200px;height:150px;margin:5px;position:absolute;left:0px;top:0px;">
</div>
<div id="2" class="item" style="background:#aaccff;float:left;width:200px;height:150px;margin:5px;position:absolute;left:210px;top:0px;">
</div>
<div id="3" class="item" style="background:#ffccaa;float:left;width:200px;height:150px;margin:5px;position:absolute;left:420px;top:0px;">
</div>
</div>
I want to remove first div in #main after some animation
I wrote jquery
$('#leftbutton').click(function() {
$('#main').append('<div id='+ i++ +' class="item" style="background:#ffccaa;float:left;width:200px;height:150px;margin:5px;position:absolute;left:630px;top:0px;z-index:1"></div>');
$('.item').animate({
"left": "-=210px"
}, 200, function(){
$('#main div:first-child').remove();
});
});
});
But it also removes all other divs. I only want to delete 1st div, how can i do that
example http://jsfiddle.net/Ks6K6/2/
EDIT
I needed to save the reference for the first element then do animation for all divs and after that remove the first div by reference
I think the problem you have is that you’re animating on all of your child elements, and for each of those animations, you’re passing a callback that executes when it completes that removes the first element. You’re essentially doing “remove the first element”
xnumber of times, wherexis the number of elements being animated.So the first elements animation completes, removing the first child. The second elements animation completes, and it also removes the first child (what was previously the second child), etc.
I would store the reference to the specific element you want to remove before calling
.animate(), then use that variable to perform the removal.Broken DEMO
Fixed DEMO