I am creating a utility method which helps fading the elements sequentially with jQuery. As you can see in the below code I am adding an extra class as alreadyFadedIn
a flag. At the end of the method call sequentiallyFadeIn(...)
I would like to perform the cleanUp
where I want to remove the flag class which I added in the selected elements inside the sequentiallyFadeIn(...)
method.
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function sequentialFadeIn(selectorText, speed, display, callBack) {
display = typeof display !== 'undefined' ? display : "block";
function helper() {
nextElementToFadeIn = $(selectorText).not(".alreadyFadedIn").first();
nextElementToFadeIn.fadeIn(speed, function() {
$(this).addClass("alreadyFadedIn");
helper();
}).css("display", display);
}
helper();
callBack(selectorText);
}
sequentialFadeIn(".toBeFaddedIn", "slow", "inline-block",function cleanUp(selectorText1){
$(selectorText1).removeClass("alreadyFadedIn");
console.log("Clean up has been performed.");
console.log("Selector Text: " +selectorText1);
} );
});
</script>
</head>
<body><style media="screen" type="text/css">
.hello {
background-color: blue;
height:50px;
width: 50px;
display: none;
}
</style>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
<div class="hello toBeFaddedIn"></div>
</body></html>
While looking at the inspect element I notice that class alreadyFadedIn
is not getting removed. The cause seems to me is the cleanUp method gets executed asynchronously along with main logic of the sequentiallyFadeIn
method which is in helper()
. You can also notice the log message "Clean up has been performed." getting printed even before the divs have completed fading in.
How can I make the cleanUp
call getting executed after the completion of main logic in the sequentiallyFadedIn
method? Any suggestions?
Code on jsfiddle: http://jsfiddle.net/BztLx/11/