Reputation: 393
I am removing a bunch of div elements using jquery. What I want is when The div is removed then the rest of the div elements should animate to the top. My current code just removes it and the rest of the div elements shift immediately. How can I achieve this?
Below is my code
HTML
<div class="div"><a href="#" class="remove">Remove</a></div>
<div class="div"><a href="#" class="remove">Remove</a></div>
<div class="div"><a href="#" class="remove">Remove</a></div>
<div class="div"><a href="#" class="remove">Remove</a></div>
JS
$('.remove').on('click', function () {
$(this).parent().remove();
});
CSS
.div {
padding: 20px;
margin-bottom: 20px;
background: #ccc;
-webkit-transition: all 2s; /* For Safari 3.1 to 6.0 */
transition: all 2s;
}
Upvotes: 0
Views: 65
Reputation: 3032
Here is a solution for your issue:
Updated JS:
$('.remove').on('click', function () {
var $elem = $(this).parent();
$elem.addClass('removing');
setTimeout(function () {
$elem.remove();
}, 500);
});
Updated CSS:
.div {
padding: 20px;
margin-bottom: 20px;
background: #ccc;
transition: width 2s, height 0.5s, opacity 0.5s, margin 0.5s, padding 0.5s;
}
.removing {
height: 0;
opacity: 0;
padding-top: 0;
padding-bottom: 0;
margin-top: 0;
margin-bottom: 0;
}
I included margin and padding animation to prevent any jumps on element removal. It's also important to note that I use a setTimeout
to wait for the CSS animation to finish before actually removing the element. If you're not concerned with the elements being removed from the DOM, and are okay with them remaining invisible on the page, you can remove that part altogether.
Upvotes: 1
Reputation: 2105
You don't need CSS transition to do that, try :
$('.remove').on('click', function () {
$(this).parent().hide(300, function(){
$(this).remove();
});
});
Fiddle: http://jsfiddle.net/YwWn5/4/
Upvotes: 0
Reputation: 1400
this will do the trik
$('.remove').on('click', function () {
$(this).parent().slideUp("slow", function(){
$(this).remove();
});
});
Upvotes: 1