Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify event data during propagation

Is there any way of attaching data to a jQuery event object as it propagates up the DOM?

To clarify, if you have three nested divs, each with a click event listener, then clicking on the innermost div results in all three handlers being called from the innermost to the outermost (event propagation 101). What I'd like to do is add some data to the event object in each handler that's accessible to the next layer up.

How do I do that?

like image 470
nicholas Avatar asked Aug 19 '11 06:08

nicholas


People also ask

What are the three phases of event propagation?

The standard DOM Events describes 3 phases of event propagation: Capturing phase – the event goes down to the element. Target phase – the event reached the target element. Bubbling phase – the event bubbles up from the element.

What is event propagation how can we stop event propagation?

The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

How do events propagate?

Event propagation is a way to describe the “stack” of events that are fired in a web browser. In our table example above, clicking on the a tag is the first event that we will fire, but there are other events too. To understand that concept, you must understand that the elements on a web browser are nested.

How does event propagation work Javascript?

In the capturing phase, events propagate from the Window down through the DOM tree to the target node. For example, if the user clicks a hyperlink, that click event would pass through the <html> element, the <body> element, and the <p> element containing the link.


2 Answers

The event object that is passed by jQuery is a wrapper around the native event object. The bubbling happens at the javascript/browser level and hence the native event object seems to be shared among all the event handlers.

$('div').click(function(e) {     e.originalEvent.attribute =  (e.originalEvent.attribute || "") +          " " + $(this).prop("className");     alert(e.originalEvent.attribute); }); 

Tested in Chrome, Firefox, Safari, IE9 and IE10. If you test in other browsers please comment with the results.

Here's the fiddle: http://jsfiddle.net/5AQqD/

like image 75
digitalPBK Avatar answered Sep 16 '22 15:09

digitalPBK


Although you cannot attach data directly to the event, you could still attach data to the targetElement via jQuery's data():

$('div').click(function(e) {     var info = $(e.target).data('info') || '';     $(e.target).data('info', info + ' ' + $(this).attr('class')); }); 

Here's the fiddle: http://jsfiddle.net/eKVmU/

like image 43
Joseph Silber Avatar answered Sep 19 '22 15:09

Joseph Silber