Test If Event Handler Is Bound to an Element in Jquery

test if event handler is bound to an element in jQuery

You can get this information from the data cache.

For example, log them to the console (firebug, ie8):

console.dir( $('#someElementId').data('events') );

or iterate them:

jQuery.each($('#someElementId').data('events'), function(i, event){

jQuery.each(event, function(i, handler){

console.log( handler.toString() );

});

});

Another way is you can use the following bookmarklet but obviously this does not help at runtime.

How to check if element has click handler?

You can use jQuery._data to check for events. The first argument should be a reference to the HTML element, not the jQuery object.

var ev = $._data(element, 'events');
if(ev && ev.click) alert('click bound');

Sample below.

$(function(){    $('#test').click(function(){        // NOTE: this below is refering to the HTML element, NOT the jQuery element        var ev = $._data(this, 'events');        if(ev && ev.click) alert('click bound to this button');    });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><button id="test">Click me to check for click handlers</button>

How to check if click event is already bound - JQuery

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);
}

How to check if an jQuery event is bound to an element from a cypress test

Instead of directly testing that the event exists, you could use Cypress retry-ability to keep testing the event's affect, something like

cy.get('.element-that-changes-after-event').then($target => {
// use closure to get a reference to changing element

cy.get('.element-being-tested')
.should($clickable => { // .should(cb) callback function will be retried

$clickable.click()
expect($target.text()).to.equal('Content that appears after click event')

});

});

See Assert class name contains heading-

There may be a simpler way to do this, please post your test.

Check if event exists on element

$('body').click(function(){ alert('test' )})

var foo = $.data( $('body').get(0), 'events' ).click
// you can query $.data( object, 'events' ) and get an object back, then see what events are attached to it.

$.each( foo, function(i,o) {
alert(i) // guid of the event
alert(o) // the function definition of the event handler
});

You can inspect by feeding the object reference ( not the jQuery object though ) to $.data, and for the second argument feed 'events' and that will return an object populated with all the events such as 'click'. You can loop through that object and see what the event handler does.

Can I find events bound on an element with jQuery?

In modern versions of jQuery, you would use the $._data method to find any events attached by jQuery to the element in question. Note, this is an internal-use only method:

// Bind up a couple of event handlers
$("#foo").on({
click: function(){ alert("Hello") },
mouseout: function(){ alert("World") }
});

// Lookup events for this particular Element
$._data( $("#foo")[0], "events" );

The result from $._data will be an object that contains both of the events we set (pictured below with the mouseout property expanded):

Console output for $._

Then in Chrome, you may right click the handler function and click "view function definition" to show you the exact spot where it is defined in your code.

Pragmatically test if specific event handler(function) is bound to an object's event using jQuery

Here is a solution that worked for me. I used this stackoverflow answer (https://stackoverflow.com/a/2518441/2512022) to create the following function to test if a object has a specific handler bound to a specific event.

This function take a Object, Event Name, and handler function name as input parameters and will return true/false if the function is bound the event on the object passed in.

function testHandler(obj, sEvent, sHandlerName)
{
var retVal = false;

// Get all events bound to object
var windowEvents = jQ._data(obj, "events");

// Get all handlers for a specific event
var handlers = windowEvents[sEvent];

jQ(handlers).each(function() {
// Using passed name to see if there is a match
if(this.handler.name === sHandlerName)
{
retVal = true;
return;
}
});

return retVal;
}

Then call the function as follows.

// Test if there is a beforeclose() handler bound to the window objects
// "beforeunload" event

testHandler(window, "beforeunload", "beforeclose");

You could even test if there is on anonymous handler attached to an event. In the call below "this" references a button, and we are testing if there is an anonymous hanlder attached to the buttons click event

testHandler(this, "click", "anonymous");

What's better: Test if event handler is bound or use .off() directly

use a namespaced event with .off() because if there is some other click handler added by some other code it is prone to bugs

$('#element')
.off('click.me')
.on('click.me', function () {
// do something
console.log('clicked');
});

How to check if event handlers are already binded to an element?

The easiest approach would be to unbind the event and re-bind it again:

$(window["tdImg_"+i]).add(window["tdImgSize_"+i]).unbind('click').bind('click', toggleImageSize);

Otherwise, you'd have to access the events data, using $(el).data("events"), and manually detect if the event was already bound. Also note that this approach excludes inline event handlers.



Related Topics



Leave a reply



Submit