简体   繁体   中英

Stop .click function if user clicks many times

How to stop .click function if user clicks too many times? My code:

$('button').click(function() {
    $('#bg').fadeToggle('200');
});

jsfiddle DEMO

After more than 5 clicks it wil stop executing the function: http://jsfiddle.net/1dc8u7ms/1/

  var counter = 0;
    $('button').click(function() {
        if(counter > 5){return};
        $('#bg').fadeToggle('200');
        return counter++;
    });

Try to do it using one

$( "#foo" ).one( "click", function() {
 $('#bg').fadeToggle('200');
});

See DOC

Try something like this:

var maxclicks = 5,
    clicks = 0,
    handler = function() {
        if(clicks < maxclicks){
            $('#bg').fadeToggle('200');
            clicks++;
        }    
        else{
            console.log('You have reached the limit of '+ maxclicks + ' clicks.');
            $('button').off('click',handler)
        }

    };

$('button').on('click',handler);

I assume you're asking this because the fadeToggle animation isn't behaving.

You can control running/queued animations with .stop([bool], [bool])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM