Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create smooth transition of block elements when removing sibling elements from DOM

I have a container that is working similar to notifications in mac os - elements are added to the queue and removed after a certain timeout. This works great but has one jarring visual side effect.

When they are removed from the DOM there is a jagged update to the UI as the next element in the stack fills the void created by the previous element. I would like the elements below in the stack to move up into that space smoothly, ideally with css3 but adding a transition: all 0.5s ease-in-out to the .notice class had no effect on the object when its sibling was remove.

Minimal JS interpertation :

$('#add').click(function(e) {
    e.preventDefault();
    $('#container').append('<p class="notice">Notice #</p>');
});

$('body').on('click','p.notice', function(e) {
    $(this).fadeOut();
});

Better yet fiddle here :

http://jsfiddle.net/kMxqj/

I'm using a MVC framework to data-bind these objects so some native css / jQuery is preferred over a Jq plugin.

like image 275
jarmie Avatar asked Mar 12 '13 16:03

jarmie


2 Answers

This should remove the clicked element with a fade out effect and then move everything below up smoothly. This will work for any notice div in the stack regardless of it position within the stack.

Try:

$('body').on('click','p.notice', function(e) {
    $(this).fadeOut(500,function(){
        $(this).css({"visibility":"hidden",display:'block'}).slideUp();
    });
});

Fiddle here

Update August 7th, 2018:

As asked by one of the users about using pure JS to do the slideUp functionality, I've put together a quick demo using requestAnimationFrame to animate the height of an element. Fiddle can be found here.

like image 57
darshanags Avatar answered Oct 23 '22 14:10

darshanags


jQuery's Animate() method is a great tool to learn because not only can you fade your objects in and out, but you can move them around, all at the same time.

The CSS:

.notice {
    position:relative;
    top:20px;
    width: 100%;
    height: 50px;
    background-color: #ccc;
    opacity:0;
}

The jQuery:

$('#add').click(function(e) {
    e.preventDefault();
    $('#container').append('<p class="notice">Notice #</p>');
    $('.notice').animate({opacity: 1, top:0}, 1000);
});

$('body').on('click','p.notice', function(e) {
    $(this).fadeOut();
});

And my jsFiddle demo

like image 34
klewis Avatar answered Oct 23 '22 14:10

klewis