Search code examples
javascriptjqueryhtmlclickslide

JQuery : how to limit CLICK (make slides)?


My problem is if I press the "button" in rapid succession very fast, Images overlap. and if I press the "button" in rapid succession very fast, I stopped pressing the button, but the Slides will continue to work.

For example, if I press the button 20 times quickly, the image will overlap and the slide will work 20 times, slower than the button pressed speed. So I would like to prevent the click method from running while the slide is moving by clicking on the "button". What should I do?

$(function(){
    var max =  $("header > img").length -1;
    var sno = 0;
    $("button").on("click",function(){
        $( $("header > img")[sno] ).animate({
            left: "100%"
            },1000,function(){
            $(this).css({left: "-100%"});
        });
        sno++;
        if( sno > max ) sno = 0;
        $( $("header > img")[sno] ).animate({
            left: "0%"
        },1000);
    });
});

Solution

  • You can set disable to button when button clicked.

    $(function(){
        var max =  $("header > img").length -1;
        var sno = 0;
        $("button").on("click",function(){
            var button = this;
            $(button).prop('disabled', true);
            $( $("header > img")[sno] ).animate({
                left: "100%"
                },1000,function(){
                $(this).css({left: "-100%"});
                $(button).prop('disabled', false);
            });
            sno++;
            if( sno > max ) sno = 0;
            $( $("header > img")[sno] ).animate({
                left: "0%"
            },1000,function(){
                $(button).prop('disabled', false);
            });
        });
    }
    

    And release it in complete callback function.