Search code examples
javascriptjqueryslidetoggle

How to change/remove class when close SlideToggle


I want to remove the ativo class from liToggle when close my SlideToggle. I've tried to use is(":hidden") and the ELSE statement, but doesn't work.

How can i do this?

$("aside #menu-busca ul > li a").click(function(){
    if($(this).attr('href') == "#"){

        var ulToggle = $(this).parent().children("ul");
        var liToggle = $(this).parent();
        ulToggle.slideToggle("slow");

        if (ulToggle.is(":visible")){
            $(liToggle).addClass("ativo");
        }
        // * Here?
        else {
            $(liToggle).removeClass("ativo");
        }

        return false;
    }
});

I have a codepen here too... can be useful: http://codepen.io/maykelesser/pen/RKdgvY


Solution

  • You'll have to wait till slideToggle() animation actually completes to determine whether it's :visible or not.

    You can pass a callback:

    var ulToggle = $(this).parent().children("ul");
    var liToggle = $(this).parent();
    
    ulToggle.slideToggle("slow", function() {
        if (ulToggle.is(":visible")){
            $(liToggle).addClass("ativo");
        }
        else {
            $(liToggle).removeClass("ativo");
        }
    });
    
    return false;
    

    Or use a Promise:

    ulToggle.slideToggle("slow").promise().then(function() {
        if (ulToggle.is(":visible")){
            $(liToggle).addClass("ativo");
        }
        else {
            $(liToggle).removeClass("ativo");
        }
    });
    

    Also, you can avoid the entire if clause using:

    $(liToggle).toggleClass("ativo", ulToggle.is(":visible"));