Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate elements move with css3 transitions after hiding some element

Is it possible to animate elements move with css3 transitions after hiding some element using jQuery's .fadeOut()?

I found some kind of solution here (see "It works for grids, too" section):

However my case is more like this: http://jsfiddle.net/CUzNx/5/

<div class="container">
    <div id="item1" class="item">Test1</div>
    <div id="item2" class="item">Test2</div>
    <div id="item3" class="item">Test3</div>
    <div id="item4" class="item">Test4</div>
    <div id="item5" class="item">Test5</div>
    <div id="item6" class="item">Test6</div>
    <div id="item7" class="item">Test7</div>
</div>

<div style="clear:both">
<button onclick="$('#item1').fadeOut();">
   Hide first
</button>
<button onclick="$('#item1').fadeIn();">
   Show first
</button>
</div>

I have floating div elements and after some element is hidden, it would be nice if other elements were animated. Is it possible?

like image 699
Lauri Avatar asked Aug 21 '13 18:08

Lauri


1 Answers

You could do something like this which uses a CSS class toggled by a little JavaScript and CSS transitions to do what you're looking for instead of using jQuery.

// The relevant CSS
.item {
    // Your original code here
    -webkit-transition: all .5s ease-in-out;
    -moz-transition: all .5s ease-in-out;
    -o-transition: all .5s ease-in-out;
    transition: all .5s ease-in-out;
}
.hide {
    width: 0;
    height: 0;
    opacity: 0;
    margin: 0;
    padding: 0;
}

// The JavaScript
var items = document.getElementsByClassName('item');
for(var i = 0; i < items.length; i ++) {
    items[i].onclick = function() {
        this.classList.toggle('hide');
    }
};

function addBack() {
    for(var i = 0; i < items.length; i ++) {
        items[i].classList.remove('hide');
    }
}

I also took out your buttons and added an "Add all elements back" button:

<button onclick='addBack()'>Add all elements back</button>

If you're already using jQuery somewhere else in your project I also made this jQuery version. Here is the JavaScript for that:

function addBack() {
    $('.item').each(function() {
        $(this).removeClass('hide');
    });
}

$('.item').on('click', function() {
    $(this).toggleClass('hide');
});

Also, you don't need IDs for any of this, so they can be taken out if you so please.

like image 126
Zach Saucier Avatar answered Oct 02 '22 15:10

Zach Saucier