Fade out divs one at a time using JQuery

260 views Asked by At

I have this function that fades out each div apart from the one that has been clicked on. At the moment they all fade out at the same time, but I would like them to fade out one at a time.

I would also like the divs to fade out in a random order so extra points to anyone who can tell me how!

$(".grid-item").click(function () {

  var selected = this;

  $('.grid > div').not(selected).each(function(i) {
    $(this).fadeTo(200, 0, function(){
      $(this).css("visibility", "hidden");
    });
  });

});
3

There are 3 answers

0
omikes On

This is a bit lengthy, but I like it because it uses a recursive function to randomize the delay of the fades:

var doms = [];
var randos = [];
var index = 0;

$(".grid-item").click(function () {
    var selected = $(this);
    doms = $('.grid > div').not(selected);
    var num = Math.floor(Math.random() * doms.length);
    for (var i = 0; i < doms.length; i++)
    {
        while (randos.indexOf(num) > -1)
        {
            num = Math.floor(Math.random() * doms.length);
        }
        randos.push(num);
    }
    fadeout();
})

window.fadeout = function () {
    if (doms.length > 0) {
        var random = $(doms.get(randos[index]));
        $(random).delay(200 * index).fadeTo(200, 0, function () {
            $(random).css("visibility", "hidden");
        });
        doms = doms.not(random);
        index++;
        fadeout();
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid">
    <div class="grid-item">hello</div>
    <div class="grid-item">how</div>
    <div class="grid-item">are</div>
    <div class="grid-item">you</div>
    <div class="grid-item">today</div>
</div>

2
A. Wolff On

This is logic you can use: link

$(document).ready(function () {
    $(".grid-item").click(function () {
        var selected = this;
        var queue = $.Deferred().resolve(); // create an empty queue
        $('.grid > div').not(selected).get().forEach(function (div) {
            queue = queue.then(function () {
                return $(div).fadeTo(200, 0).promise();
            })
        });
    });
});

DEMO with bonus randomizing array: jsFiddle

0
Armand On
var selected;

var fader = function() {
    $('.grid > div').not(selected).not(':hidden').first().fadeOut(200, fader);
};

$(".grid-item").click(function () {
    selected = this;
    fader();
});

For the randomness, have a look at:

http://blog.mastykarz.nl/jquery-random-filter/

Please give me the bonus points.