[ACCEPTED]-jQuery toggle and IF visible-toggle

Accepted answer
Score: 45

You need to use the callback function. By 3 the time the if statement is evaluated the 2 slideToggle will not have completed and 1 you will get incorrect results.

$("#moreOptions").slideToggle('slow', callbackFn);

function callbackFn(){

     var $link = $("#lnkMoreOpt");

     $(this).is(":visible") ? $link.text("Less Options «") : $link.text("More Options »");


}
Score: 4

I think this code will work

$('#element').toggle('slow', function() {
    if($(this).is(':hidden')) { 
        $(this).text('This element is hidden.');
    }
    else {
        $(this).text('This element is visible.');
    }
}); 

0

Score: 1

I prefer not to use separate functions because 4 when one function does not need to be used 3 twice, it is waste of code.. i believe this 2 is easier to understand when someone comes 1 to it..

$("#moreOptions").slideToggle('slow', function(){
     var $link = $("#lnkMoreOpt");
     $(this).is(":visible") ? $link.text("Less Options «") : $link.text("More Options »");
});

More Related questions