Discovering the events attached to elements in jQuery

If you have a need to find what events are attached to an element in jQuery, here’s what you do:

Finding events attached to the document:


jQuery._data( jQuery( document )[0], 'events' );

Finding events attached to an element with an ID of bacon:


jQuery._data( jQuery( '#bacon' )[0], 'events' );

Here’s a snippet I’ve been using in the console:

var events = jQuery._data( jQuery( document )[0], 'events' );
for ( var i in events.click ) {
  console.log( 'click ' + i + ' :: ' + events.click[ i ].selector );
}

Oooo event:Selectors for Prototype

event_selectorsMy article on the Separation of Layout and Logic touched on a key point of heavy Javascript use in an Ajax rich environment…the need for separation of Javascript code – namely events – from the HTML. Behaviour was my suggested CSS/Javascript event selector framework.

Behaviour is a stand-alone event framework. You can use it regardless of whether or not you are using Prototype (or some other Ajax/Javascript library) – which is pretty cool. But…if you are using Prototype there is a lot of code duplication between the two libraries. Luckily, Mir.aculo.us has brought event:Selectors to my attention which is causing me to sing a different tune! Justin Palmer, event:Selector’s creator is crediting Behaviour for the idea, but he’s has what Behaviour has done a few steps further.

  • event:Selectors is dependant on Prototype which reduces code duplication.
  • It has reduced the layer of complexity of event selecting by one layer of abstraction.
  • The framework allows concatenation of CSS elements for event assignment.
  • Lastly, its added a loaded event that is triggered when an element loads.

Here’s an example of Behaviour event handlining:

  var rules = {
    '#item li': function(element) {
      Event.observe(element, 'click', function(event) {
        var element = Event.element(element);
        element.setStyle('color': '#c00');
      });
    },
    
    '#otheritem li': function(element) {
      Event.observe(element, 'click', function(event) {
        var element = Event.element(element);
        element.setStyle('color': '#c00');
      });
    }
  };
  Behaviour.register(rules);

Here’s the equivalent in event:Selectors:

  var Rules = {
    '#item li:click, #otheritem li:click': function(element) {
      element.setStyle('color': '#c00');
    }
  };

EventSelectors.start(Rules);

Simplification makes me happy. I’m a convert.