Search code examples
javascriptjqueryaccordionjquery-callback

Run function after another is finished on accordion-like tabs


I am trying to do something like an accordion effect. When you click on a "tab" it should close the one that is already open and THEN open the one that was clicked. But what is happening is that it is first opening the one clicked, and THEN closing the one that was already open.

You can see it here: https://boguz.github.io/SWCanonTimeline/

I am using the following jQuery:

// DOCUMENT READY FUNCTION
$(document).ready(function () {

// CLICK ON STRIPE
$(".stripe").on("click", function() {

    closeStripe();

    openStripe( $(this) );

});

}); // end of document.ready


// CLOSE OPEN STRIPE
function closeStripe() {

    $(".open").removeClass("open");

}

// OPEN CLICKED STRIPE
function openStripe(stripe) {

    stripe.addClass("open");

}

I have tried using $.when().done() but didn't manage to make it work. I also tried making it a callback function but without success.


Solution

  • I ended up following Terry's advice and I used the toggleSlide function from jQuery to animate the tabs.

    Here is the code I am using now:

    // DOCUMENT READY FUNCTION
    $(document).ready(function () {
    
        // on tab click
        $(".stripe").on("click", function() {
    
            // close all open tabs
            $(this).siblings().children(".content").slideUp();
    
            // open just clicked tab
            $(this).children(".content").slideToggle();
    
        });
    
    }); // end of document.ready