Question

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.

Was it helpful?

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");
        }
     });
});

OTHER TIPS

It is because when you slideToggle back , the mobileMenu is still visible (during the animation).

You have to check if mobileMenu is visible before the animation.

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

you can find information on here

.slideToggle() is an asynchronous operation. Add a complete callback to .slideToggle() using your above logic as the callback function:

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");
        }
    });
});

Reference: .slideToggle(...)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top