markzzz
markzzz

Reputation: 47945

How to call a function after a fadeOut() on many elements

I have this code :

$('.hotel_photo_select').fadeOut(500, function () {
    alert("Now all '.hotel_photo_select are hidden'");
});

and I'd like to call that alert only when ALL .hotel_photo_select are fadeOuted (so, Hidden).

How can I do it? With my code the alert is called after the first element is fadeout...

Upvotes: 33

Views: 32552

Answers (3)

BrokenGlass
BrokenGlass

Reputation: 160862

You can use the promise() method for this (the doc page has a good example for this).

The .promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended.

Applied to your example should be something like this:

$.when(
    $('.hotel_photo_select').fadeOut(500)
).done(function() {

    alert("Now all '.hotel_photo_select are hidden'");

});

OR

$('.hotel_photo_select').fadeOut(500)
    .promise().done(function() {
        alert('Got this far!');
    });

Upvotes: 74

Tigran Zalian
Tigran Zalian

Reputation: 51

$(element).fadeOut(duration, onComplete)

Example:

$('#box').fadeOut(400, () => { console.log('Fade effect is done') })

Upvotes: 5

Rehan Shah
Rehan Shah

Reputation: 1627

Using jQuery $.when().then() functions.

$(document).ready(function(){
  // using When & then methods.
  $.when($('.box').fadeOut())
   .then(function(){
      alert("All Boxes : Faded Out.");
   });
});
.box{
    color: white;
    background-color: red;
    width: 100px;
    height: 100px;
    text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <head>
    <title>Calling Alert After fadeOut</title>
  </head>
  <body>
    <div class="box">Box 1</div> <br />
    <div class="box">Box 2</div> <br />
    <div class="box">Box 3</div> <br />
    <div class="box">Box 4</div> <br />
    <div class="box">Box 5</div>
  </body>
 </html>

Upvotes: 2

Related Questions