JQuery 3 - Reinventing Events
Written by Ian Elliot   
Monday, 03 April 2017
Article Index
JQuery 3 - Reinventing Events
Bubbling & Capture
Event Data
Bubbling & Delegation

The jQuery event system is very general and it even works with standard JavaScript and DOM objects. For example:

var obj=$({}).on("myevent",function(event,param1,param2){
                               alert(param1 + param2);


In this case the event handler is attached to the empty object and we trigger the same event on that object. 

Not only will trigger fire event handlers that you have attached to an object it will also attempt to run properties with the correct name as functions. 

If an object has a property that is the same name as the event then it will be run as a method i.e. without any event parameters. 

If an object has a property that has "on" in front of the event name then this will be run as an event handler. That is it will be called with an event object and any custom parameters you might have defined. 

This calling of properties can be useful but it can also cause problems. To avoid calling any properties the might have the same name has an event you can use the triggerHandler function in place of trigger. 

Notice that triggerHandler will not call any methods called event but will call any methods called onevent as event handlers. It also only operates on the first element of any list of matched elements. Also it doesn't bubble events, see later, and it returns the last event handler's result not a jQuery object. 

The main use of custom events is to provided an organized way of passing information about the state of any custom component you might implement. For example, you might implement a custom dataChange event if your component is updated by the user or an outside entity. This would allow a programmer using your component to write code that could react to the change without having to get involved in the internals of your component. Custom events can also be useful in JavaScript libraries that don't implement a UI. For example you could have an event that indicated an error condition or that something was complete in an object that implemented some numerical procedure.

Bubbling  & Delegation

We have already discussed the idea of event bubbling in the context of the DOM. jQuery takes this a little further. You can use the selector part of the on function call to control the way that an event handler behaves during event bubbling.

If you don't specify a selector then you get the classical bubbling behaviour. That is the event handler is attached to each element in the jQuery results. It is fired when an event occurs on that element or bubbles up to that element as a result of an event on a child element. 

To illustrate this we can re-implement the earlier example but using jQuery:

<div id="div1">
Some Text
 <button id="button1">
 Click me

$("#div1").on("click",function(){alert("div");}); $("#button1").on("click",function(){alert("button");});


If you click on the button then you will see the button message followed by the div as the event bubbles up. If you click on the div you will only see the div message. 

We can use this to find out about the information about the event passed in the event object:

                 alert($(event.target).attr("id"));}); $("#button1").on("click",function(event){

Now if you click in the button you will see the button1 message twice once from the button's event handler and once from the div's event handler. The target is the button in both cases. 

If you change the code to:

        alert($(event.currentTarget).attr("id"));}); $("#button1").on("click",function(event){

you will see button1 followed div1 as currenTarget gives the element the event handler invoked by the bubbling is attached to.

Notice that you can stop bubbling by calling the event object's stopPropagation or by just returning false.  Notice that this doesn't stop any other event handlers on the same element from running - just the bubbling of the event. If you want to stop everything after the current handler, other event handlers and bubbling, then use stopImmediatePropagation. Notice that this is the only way to stop event handlers on the same element from running. The reason is that the list of handlers to run is constructed when the event occurs and, if you remove an event using off, this does not remove it from the list of event handlers to run. The removal will only have an effect when the event next occurs. 

This is just standard HTML event bubbling implemented by jQuery. If you specify a selector then you get something different. What happens is that if a child element matches the selector then the parent will provide the event handler for the event. This is called a delegated event handler. Notice that, unlike the default bubbling, the child element doesn't have an event handler of its own. 

An example will help make delegation clear:


Notice that now we have specified a selector "button". This means that any event that occurs on a button that is contained within the div will be handled by the event handler. Now if you click on the button you will see the button1 message and no div1 message. What might be more surprising is that you don't see anything if you click on the div.

In this case the div's event handler is only handling events on any button objects the div contains. 

This is a particularly useful feature if you plan to dynamically add elements into  the container because the event handler will be called for events on elements that didn't exist when it was attached to the container. 

It is fairly easy to understand how delegation works. When you click on the button it doesn't have an event handler attached so no event handler is called but the event still bubbles up to the div. At this point jQuery intercepts it and check to see if there is a delegated event handler that matches the event and the element that the event occurred on. If so the delegated event handler is called.  

You also need to know that in this case target is button1, currentTarget is the element that the delegated event is handling  i.e. button1 and delegateTarget is the element that the handler is actually attached to i.e. div1.

Also notice that this is the same as target for direct and delegated events.


Now Available as a Print Book: 



You can buy it from:

USA and World     Amazon.com
Canada            Amazon.ca

UK                Amazon.co.uk
France            Amazon.fr
Germany           Amazon.de
Spain             Amazon.es
Italy             Amazon.it
India             Amazon.in
Japan             Amazon.jp

The Core UI

  1. Understanding jQuery (Book Only)
  2. The DOM And Selectors
  3. CSS Selectors
  4. The jQuery Object (Book Only)
  5. Filters
  6. Advanced Filters - Traversing The DOM
  7. Modifying DOM Objects
  8. Creating And Modifying The DOM
  9. jQuery Data
  10. Forms
  11. Function Queues
  12. Animation
  13. jQuery UI
  14. jQuery UI Custom Control - Widget Factory
  15. jQuery - Easy Plugins
  16. Getting Started With QUnit Testing

Now Available as a Print Book:


jquery2coverYou can buy it from:

USA and World   Amazon.com
Canada          Amazon.ca
UK              Amazon.co.uk
France          Amazon.fr
Germany         Amazon.de
Spain           Amazon.es
Italy           Amazon.it
India           Amazon.in


Events, Async & AJAX

  1. Events, Async & Ajax (Book Only)
  2. Reinventing Events
  3. Working With Events
  4. Asynchronous Code
  5. Consuming Promises
  6. Using Promises 
  7. WebWorkers
  8. Ajax the Basics - get
  9. Ajax the Basics -  post
  10. Ajax - Advanced Ajax To The Server
  11. Ajax - Advanced Ajax To The Client
  12. Ajax - Advanced Ajax Transports And JSONP
  13. Ajax - Advanced Ajax The jsXHR Object
  14. Ajax - Advanced Ajax Character Coding And Encoding 



JavaScript Canvas - Animation

Canvas animation is simple - or is it? Just keep drawing the pictures. In this extract from JavaScript Bitmap Graphics With Canvas we look at how it works.

JavaScript Jems - The Proxy

The proxy is a mysterious object that lurks behind other objects - the question is why? This is an extract from my newly published book, JavaScript Jems: The Amazing Parts.

Other Articles

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.





or email your comment to: comments@i-programmer.info

Last Updated ( Tuesday, 25 April 2017 )