luetkemj
luetkemj

Reputation: 171

Callback function in for loop?

How do I get a function to run after all the fadeOuts in the for loop below?

What I need to do is fadeout anything that may be visible and then fadein a specific object. Due to styling requirements my topnav and dropdown nav are in to different uls which is why things are tricky.

I'm not very good at writing my own scripts yet so I'm (hopefully) missing something basic.

I've tried wrapping things in functions but that seems to mess with variable scope and screws things up that I don't understand...

Thanks for any help!

$('.ksddtop').on('mouseenter', function(){
    var ddtop = $(this).text();
    var dd = $('.' + ddtop);
    $('.ksddwrap').fadeIn();
    $(dd).fadeIn();

    var ksdds = $('.ksdd');
    for(var i = 0; i < ksdds.length; i++) {
        var ksdd = ksdds[i];
        if (! $(ksdd).hasClass(ddtop) ){
            $(ksdd).fadeOut();
        }
    }
}); 

Upvotes: 3

Views: 311

Answers (2)

Kevin B
Kevin B

Reputation: 95030

This should do it, if I understand the requirements:

$('.ksdd:not(' + ddtop + ')').fadeOut().promise().done(function(){
    // all done fading!
});

Fade out all ksdd elements that don't have the ddtop class, then do something when they are all done animating.

More Information:

calling .promise on a jQuery collection gives you a promise object that will resolve when all animations on the collection of elements are complete. This includes queued animations.

If you instead passed a callback function directly to .fadeOut(), you would get a callback for each element rather than one after they were all done.

Upvotes: 6

Blaster
Blaster

Reputation: 9110

Instead of:

var ksdds = $('.ksdd');
for(var i = 0; i < ksdds.length; i++) {
    var ksdd = ksdds[i];
    if (! $(ksdd).hasClass(ddtop) ){
        $(ksdd).fadeOut();
    }
}

Try:

$('.ksdd').each(function(){
    if (! $(this).hasClass(ddtop) ){
        $(this).fadeOut();
    }
});

Upvotes: 1

Related Questions