Search code examples
jquery-animatetoggleremoveclass

Add Class and Perform Animation on Click, Reverse on Click Again


I have a wrap element that is hidden initially. Once clicked the hidden element needs to have a visible class added, before performing a toggle animation on another element. Then once clicked again, the animated element needs to toggle it's animation, and then remove said class from the wrap.

Here is what I have thus far. The initial click performs fine. Class is added, and animation is performed. But on click again the animation is performed properly, but once it is completed, the class is not removed.

$(document).ready(function () { 
$('.search-btn').click(function() {
    if ($('.search-form-wrap').hasClass('hidden')) {
        $('.search-form-wrap').addClass('visible', function() {
            $('.search-form').blindLeftToggle('slow'); 
        });
    }
    else {
        $('.search-form').blindLeftToggle('slow', function() {
            $('.search-form-wrap').removeClass('visible'); 
        });
    }
});
});

This seems to work based on the code from Blazemonger, with the addition of $('.search-form-wrap').hide();

$(document).ready(function () { 
$('.search-form-wrap').hide();
$('.search-btn').click(function() {
    if ($('.search-form-wrap').is(':hidden')) {
        $('.search-btn').toggleClass('active'); 
        $('.search-form-wrap').show();
        $('.search-form').blindLeftToggle('slow'); 
    } else {
        $('.search-form').blindLeftToggle('slow', function() {
            $('.search-form-wrap').hide();
        });
    }
});
});

Solution

  • That's because you're testing if it .hasClass('hidden'). If you're adding/removing the visible class, you want to test if it's .not('.visible') instead.

    UPDATE

    If, however, you meant you want to test if the element is hidden or visible WITHOUT using classes, use the :hidden and :visible selectors instead of classes:

    $(document).ready(function () { 
        $('.search-btn').click(function() {
            if ($('.search-form-wrap').is(':hidden')) {
                $('.search-form-wrap').show();
                $('.search-form').blindLeftToggle('slow'); 
            } else {
                $('.search-form').blindLeftToggle('slow', function() {
                    $('.search-form-wrap').hide();
                });
            }
        });
    });