Search code examples
javascriptjqueryslidetogglevisible

jquery toggle state not changing .text to previous value


So I'm building this menu area for mobile and I'm using the following code:

mobileMenuBtn.click(function(){
    mobileMenu.slideToggle(200);
    if(mobileMenu.is(":visible")){
        $("#alt-menu .menu-item:last-child a").text("Close");
    }
    else{
        $("#alt-menu .menu-item:last-child a").text("Menu");
    }
});

Now, the menu toggles just fine and the text changes to "Close" but when I click on it again, it doesn't change back to "Menu".

Can anyone tell me why's that?

Thanks in advance and I hope someone can learn from my question aswell.


Solution

  • slideToggle is async so your function can continue before the element is hidden/shown.

    In this case you can use the complete callback fired when the animation is complete.

    Code:

    mobileMenuBtn.click(function(){
        mobileMenu.slideToggle(200, function() {
            if(mobileMenu.is(":visible")){
                $("#alt-menu .menu-item:last-child a").text("Close");
            }
            else{
                $("#alt-menu .menu-item:last-child a").text("Menu");
            }
         });
    });