Skip to content Skip to sidebar Skip to footer

Execute A Function Only Once

I have a function which executes on click event, but the thing is that I want it to execute only once. The function that get's executed on click represents a google map plotting t

Solution 1:

Use jQuery's .one().

http://api.jquery.com/one/

As per OP's explanation: there's always the possibility to define more than one click event for an element.

So you can define one with .one() and the other with on() as you already do, putting the code to run only once in the first.

Solution 2:

you could bind click only once like:

$(document).one('click', function(e) {
    //do your code here
});

OR

$('#someBtn').click(function(){    
    if ($(this).attr('data-once')!='already_clicked' ){
        //your code here
        $(this).attr('data-once', 'already_clicked');
    }
});

Solution 3:

Two choices:

  1. Use two event handlers: one defined with one, the other with on
  2. Use a counter in the closure.

Something like:

var counter = 0;
return $(element).on('click', function() {
    counter++;
    if ( counter > 1 ) {
    }
});

Post a Comment for "Execute A Function Only Once"