views:

26

answers:

2

Hi

I'm new to javascript/jQuery this really has me stumped.

What I'm trying to achieve here is

  • On toggling a#sameDayTab jquery will look for .changeAlert and fadeOut it's container div, when toggled again the div will fade in (this works well.)
  • Each toggle will also call a function that tells me how many .changeAlert's are present on the page and updates the number appropriately in a span. The problem is when I first click the toggled anchor the number of visible should be 0 as the .changeAlert has been hidden by fadeOut instead it returns the number of classes present on page load this value never changes no matter how many times the toggle is activated.

Any help greatly appreciated.

function totalNumFares ()
    {
    var n = $('.changeAlert:visible').size();               
    $('.numFares').replaceWith('<span class=\"numFares\">'+ n +'</span>');

    }

totalNumFares();    

//Toggle On/off Same Day Connections

$('a#sameDayTab').toggle(function() {

    $('.changeAlert').parent().parent().parent().parent().parent().fadeOut();
    totalNumFares();        


    },function(){
    $('.changeAlert').parent().parent().parent().parent().parent().fadeIn();
    totalNumFares();


});
A: 

You need to set it as a callback:

$(function(){
    // You can set duration to whatever you like
    $("#item").fadeOut(duration, function(){
        totalNumFares();
    });
});

http://api.jquery.com/fadeOut/

bschaeffer
Thanks for your help works a treat.
willmcneilly
A: 

You need to run it as the .fadeOut() callback, like this:

$('.changeAlert').parent().parent().parent().parent().parent().fadeOut(totalNumFares);

Currently it executes immediate after it starts fading, but it's :visible until it finishes fading, so to have that count what you want, you need to update it after the .fadeOut() has finished, which is when the callback runs.

Also, you can likely replace that .parent() chain with a single .closest(selector) call if you have a class on that parent you can use as a selector.

Nick Craver
Works perfectly. Still finding my feet with jQuery and javascript in general. Thanks for the explanation now I know for next time.
willmcneilly