bigpotato
bigpotato

Reputation: 27507

How would I stop the click method from working more than once?

I have a click method on a button + link that animates stuff as a result of the click. However, I want it so that it only works once. I managed to disable the button after it's clicked, so that's good. But I tried .disabled = true on the link and it didn't work. Is there some way I could prevent it from being clicked more than once?

JS

$('#frontbutton, #loginlink').on('click', function(){
    $('.popup').hide();
    usernameInput.val('');
    emailInput.val('');
    passwordInput.val('');
    confirmInput.val('');
    $('.intro').animate({opacity: '0.5'}, 1000).delay(800).animate({
        left: "+=300px"
    });
    setTimeout(function(){
        $('.formholder').show()}, 2000);
    $('.toppic').animate({opacity: '0.5'}, 1000).delay(800).animate({
        top: "+=300px"
    });
    document.getElementById('frontbutton').disabled = true;
});

Upvotes: 2

Views: 101

Answers (3)

Andres Gallo
Andres Gallo

Reputation: 681

With jquery you can turn the event off this way

 $('#frontbutton, #loginlink').on('click.myEventNamespace',function(){
       //Run my code
       $('#frontbutton, #loginlink').off('click.myEventNamespace');
 });

You can also do this inside your event. Thought it may be worth knowing for when you don't use jQuery

 this.removeEventListener('click',arguments.callee,false);

Upvotes: 1

Abraham
Abraham

Reputation: 20684

Try one('click',function(){... instead of on('click',function(){.... The event will only run once per element.
Here's the documentation.

Upvotes: 1

Blender
Blender

Reputation: 298156

Just use .one() instead of .on():

$('#frontbutton, #loginlink').one('click', function(){

.one() behaves like .on(), but the handler unbinds itself once it has been called.

Upvotes: 5

Related Questions