jQuery: multiple events on the same element

jQuery allows us to attach multiple event handlers to the same element. This can be easily achieved using the bind() method and passing the event names we want to use (e.g. mouseover, click etc.) to this method. Problems arise when we want to perform different actions depending on the event type attached to our element. In this case, we can use the type property of the Event object to get the event name currently used and code accordingly. For example:

$('#test').bind('mouseover click', function(event) {
  
  
    var element = $(this);
    var evtType = event.type;
    
    switch(evtType) {
    
      case 'mouseover':
        element.fadeTo('slow', '0.5');
        break;
      case 'click':
        element.fadeTo('slow', '1');
        break;
      default:
        break;
    
    
    
    }
  
});

We've attached two event types to our element. We want two perform two actions depending of the event type in use. So we check what event type is currently used by getting the value of the type property of the Event object and perform our actions accordingly. You can see an example below.

Example

Live example

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

Leave a Reply

Note: Only a member of this blog may post a comment.