jQuery event handling

Events in jQuery are all part of the more global JavaScript Event object. jQuery mitigates the existing differences across browsers to give us full control over events. What we use in jQuery is simply a workaround that fixes browser inconsistencies in their event implementation. For example, when we use $(element).click(handler) or $(element).bind('click', handler), jQuery tries first the W3C DOM addEventListener() method if supported and, for Internet Explorer 8 and lower, uses the proprietary attachEvent() method. We may say that jQuery event handling is an extension added to the normal DOM core methods for events. Let's see some interesting features of jQuery event handling.

Event data

jQuery allows us to pass to our event arbitrary data, using the following syntax:

element.bind(eventType, data, handler)

For example:

$('div').each(function(i) {
  $(this).bind('click', {index:i}, function(event){
     alert('my index is ' + event.data.index);
  });
});   

As you can see, you first access the event object passed along the handler and then data with its members. You can find more on this subject at http://api.jquery.com/event.data/

Multiple events

Normally, JavaScript supports two kind of event bindings, inline and using an event listener. The former is pretty common:

var element = document.getElementById('test');
element.onclick = function() {
 // do something
};

This is a one-way binding: in fact, you can attach only one handler per time. If you want to attach multiple handlers for multiple events, you have to use an event listener (such as addEventListener()). jQuery keeps this distinction using the following two forms:

$('#test').click(handler);
$('#test').bind('click', handler);

Using bind() you can attach multiple events to the same element:

$('#test').bind('click mouseover', function(event) {

  var evtType = event.type;
  
  switch(evtType) {
  
    case 'click':
      // do something for click
    break;
    
    case 'mouseover':
      // do something for mouseover
    break;
    
    default:
      // falls through
    break;
  
  }

});

References

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.