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 a开发者_运维技巧fter the first element is fadeout...
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!');
});
$(element).fadeOut(duration, onComplete)
Example:
$('#box').fadeOut(400, () => { console.log('Fade effect is done') })
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>
精彩评论