April 26, 2012

fadeout and fadeIn callback function in jquery

Question by amit

i have three div with value first, second and third i want to fadeout them first and them fadein with delay function now i want that when my last div fadein then my all three div fade out. but my code in not working well

<script type="text/javascript">

$(function(){

    $('.fileianN').fadeOut().delay(1000).fadeIn(1000);
        $('.fileianLY').fadeOut().delay(2000).fadeIn(1000);
            $('.fiuleHg').fadeOut().delay(3000).fadeIn(1000);

    })


</script>





<div class="duanNt">
<div class="fileianN">first</div>
<div class="fileianLY">second</div>
<div class="fiuleHg">third</div>


</div>

Answer by roXon

jsBin demo

$.when(

    $('.duanNt').children().each(function(idx,el) {
        $(el).delay(idx*600).fadeTo(700,1);
    })

).done(function() {
    $('.duanNt').fadeTo(300,0);
});

http://api.jquery.com/jQuery.when/
http://api.jquery.com/deferred.done/

P.S if you don’t want to hide the .duanNt it self but only it’s children than use: $('.duanNt > div').fadeTo(300,0);

Answer by Starx

There is already a callback function. Which You can use like

$("element").fadeOut(1000, function() {
   //..callback
});

Your usage might be similar to this

$('.fileianN').fadeOut().delay(1000).fadeIn(1000, function() {   
     $('.fileianLY').fadeOut().delay(2000).fadeIn(1000, function() {
            $('.fiuleHg').fadeOut().delay(3000).fadeIn(1000);
     });
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!