Search code examples
javascriptjqueryslidetoggleslidedownslideup

How do I ensure that no other javascript/jQuery function doesn't happen until the other slide functions complete?


I have something that I am working on that involves the slideToggle function from jQuery. I created an example on JSFiddle. If you are on that and you click the buttons from the bottom up as fast as you can the slides happen as you click it regardless if the previous slide is completed or not. I would like to make it so that the other buttons cannot perform any actions until the slide is complete. I don't want to start a queue of actions because if you get click crazy you could create some time to wait. Are there any suggestions or tricks that could help me with this?

I am doing this because on the actual site that I am working on has a few slide actions that happen for each button. The problem is that multiple buttons share the sections that it animates. If someone clicked a couple too fast, it makes it so some of the sections disappear. I would like to make the other buttons not work until the click function is complete.

The code that I have in the JSFiddle example that toggles it is this

HTML

<section id="big1" class="big">
    <img class="bg-image" src="http://lorempixel.com/output/abstract-q-c-640-480-3.jpg" />
</section>
<section id="bar1" class="bar">
    <a id="btn-1" href="#">Button for 1</a>
</section>

jQuery

$("#btn-1").click(function () {
    $("#big1").slideToggle();
});

In the JSFiddle, these are repeated 6 times to create 6 buttons.


Solution

  • Try something like this in your JSfiddle:

    //Hide all big
    $(".big").hide();
    var slideInProgress = false;
    
    //Create button functions to toggle the slide open and close
    $(".bar > a").click(function () {
        if(!slideInProgress) {
            slideInProgress = true;
            $(this).parents('section').next().slideToggle(400, function() {
                slideInProgress = false;
            }); 
        }
    });