Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggle and IF visible

Tags:

jquery

toggle

I have a div which contains settings and options on an account management page.

$("#moreOptions").slideToggle('slow');
if ($("#moreOptions").is(":visible") == true) {
    $("#lnkMoreOpt").text("Less Options «")
}
else {
    $("#lnkMoreOpt").text("More Options »")
}

The code above should change the text of the more/less options link depending on whether it is visible or not, however it appears jQuery does not treat toggling as making it invisible/visible.

How can I implement this while still using the toggle function?

like image 963
j82374823749 Avatar asked Jul 28 '09 11:07

j82374823749


People also ask

How do I toggle show and hide in jQuery?

jQuery toggle() MethodThe toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

Can you toggle ID in jQuery?

jQuery doesnt has toggleId() function .

What is toggle () in jQuery?

The toggle() method attaches two or more functions to toggle between for the click event for the selected elements. When clicking on an element, the first specified function fires, when clicking again, the second function fires, and so on. Note: There is also a jQuery Effects method called toggle().


2 Answers

You need to use the callback function. By the time the if statement is evaluated the slideToggle will not have completed and 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 »");


}
like image 107
redsquare Avatar answered Sep 24 '22 19:09

redsquare


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.');
    }
}); 
like image 41
basim Avatar answered Sep 22 '22 19:09

basim