Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if click event is already bound - JQuery

Tags:

jquery

I am binding a click event with a button:

$('#myButton').bind('click',  onButtonClicked);

In one scenario, this is getting called multiple times, so when I do a trigger I see multiple ajax calls which I want to prevent.

How do I bind only if its not bound before.

like image 516
Dusty Avatar asked Jun 15 '11 17:06

Dusty


3 Answers

One more way - mark such buttons with a CSS class and filter:

$('#myButton:not(.bound)').addClass('bound').bind('click',  onButtonClicked);

In recent jQuery versions replace bind with on:

$('#myButton:not(.bound)').addClass('bound').on('click',  onButtonClicked);
like image 104
Konrad Garus Avatar answered Oct 18 '22 13:10

Konrad Garus


Update 24 Aug '12: In jQuery 1.8, it is no longer possible to access the element's events using .data('events'). (See this bug for details.) It is possible to access the same data with jQuery._data(elem, 'events'), an internal data structure, which is undocumented and therefore not 100% guaranteed to remain stable. This shouldn't, however, be a problem, and the relevant line of the plugin code above can be changed to the following:

var data = jQuery._data(this[0], 'events')[type];

jQuery events are stored in a data object called events, so you could search in this:

var button = $('#myButton');
if (-1 !== $.inArray(onButtonClicked, button.data('events').click)) {
    button.click(onButtonClicked);
}

It would be best, of course, if you could structure your application so this code only gets called once.


This could be encapsulated into a plugin:

$.fn.isBound = function(type, fn) {
    var data = this.data('events')[type];

    if (data === undefined || data.length === 0) {
        return false;
    }

    return (-1 !== $.inArray(fn, data));
};

You could then call:

var button = $('#myButton');
if (!button.isBound('click', onButtonClicked)) {
    button.click(onButtonClicked);
}
like image 120
lonesomeday Avatar answered Oct 18 '22 13:10

lonesomeday


If using jQuery 1.7+:

You can call off before on:

$('#myButton').off('click', onButtonClicked) // remove handler
              .on('click', onButtonClicked); // add handler

If not:

You can just unbind it first event:

$('#myButton').unbind('click', onButtonClicked) //remove handler
              .bind('click', onButtonClicked);  //add handler
like image 63
Naftali Avatar answered Oct 18 '22 13:10

Naftali