Capturing and Bubbling using jQuery - javascript

I am new to jQuery and I‘m trying to understand the concept of capturing and bubbling.
I have read a lot of articles, but most of them described event propagation for Javascript.
Lets assume we have the following HTML code:
<div id="outer">
outer
<div id="inner">
inner
</div>
</div>
Capturing is the phase where we go down the DOM elements and bubbling is when we go up.
In Javascript you can decide which way to follow (using true or false parameters):
element.addEventListener('click', doSomething, true) --> capture phase
element.addEventListener('click', doSomething, false) --> bubble phase
Is there anything similar for jQuery to denote which way to follow other than the JavaScript way?
Also does jQuery uses a default phase? For example bubble?
Because i used the following code to test this:
css
<style>
div {
border: 1px solid green;
width: 200px;
}
</style>
jQuery
<script>
$(document).ready(function(){
$('div').click(function(){
$(this).animate({'width':'+=10px'},{duration: 3000})
});
});
</script>
It appears that when I click on the outer div, only that div animates to a larger div. When I click to the inner div both divs animate to larger divs.
I don’t know if I am wrong, but this test shows that the default browser propagation method is bubble.
Please correct me if I’m wrong.

jQuery only uses event bubbling. If you want to add an event handler that uses the capturing model, you have to do it explicitly using addEventListener, with the third argument true as you show in the question.

Event bubbling which will start executing from the innermost element to the outermost element.
Event Capturing which will start executing from the outer element to the innermost element.
But jQuery will use event bubbling. We can achieve event capturing with:
$("body")[0].addEventListener('click', callback, true);
The 3rd parameter in the addEventListener which will tell the browser whether to take event bubbling or event capturing.
By default it is false.
If it is false then it will take event bubbling.
If it is true then it will take event capturing.

Question and answers live with the following misconception: that the browser does either capture or bubble.
Truth is: the browser does always both, capture and bubble, on every click, in that order.
Is there anything similar for jQuery to denote which way to follow other than the JavaScript way?
Also does jQuery uses a default phase? For example bubble?
jQuery has no event phases. The DOM has. And the DOM does always both.
But jQuery registers handlers only to the bubble phase. There is no jQuery way to register to the capture phase, so bubble registration is not a default, it is the only way (with jQuery).
I don’t know if I am wrong, but this test shows that the default browser propagation method is bubble.
You are wrong, if I’m allowed to say. When you click on the outer div, capture happens, until it reaches the outer div, then bubble... It just does not go any deeper than the actual target of the event.
If you click the inner div, capture passes the outer div, but no handler is registered there for that phase, then it reaches the target, and on the way back up (bubble) it triggers the outer div handler.—I haven’t run your code, but it would be hard to tell which one happened first (the inner is first).
(Note: once the target is reached, the phase is actually called “target phase” and handlers are called independent of which phase they registered for (in registration order, btw).)

Every Event is going first through "capturing" phase and then through "bubbling" phase.
For instance, when user clicks on <a>, all event handlers bound using "capturing" (third argument in addEventListener method set to true, not supported in jQuery) are called starting from outermost <html> all the way down to the link. Then, the "bubbling" phase starts and all event handlers using "bubbling" (supported in jQuery) are called the opposite way - from link back to the <html>.
You can try it on your own, firing this code in developer tools and clicking anywhere on your site.
document.querySelectorAll("*").forEach(it => {
it.addEventListener("click", function() {console.log("capturing: ", it)}, true);
it.addEventListener("click", function() {console.log("bubbling: ", it)}, false);
});

The event is triggered in event bubbling on the element on to which the user has clicked,and unless we call .stopPropagation() on the event object the event is then triggered all the way up the DOM.
Default is event bubbling set in Jquery in order to use Capture ypu need to set parameter as true in .addEventListner

Related

e.stopPropogation() Equivalent for Capture Phase of Click Event?

I'm looking for a way in JS to stop a click event from continuing down the DOM to a nested child element (capture phase) when the parent element was clicked.
It would be the inverse of the e.stopPropogation() function to prevent a click event from bubbling up.
Is there a native JS function for this?
Edit 03/10
Link to example
Edit 03/11
Typo in the function call - it's stopPropagation(), not stopPropogation(). Thanks to #JackPattishall for the find.
yes there is native js function for capturing event in capture phase.
In all browsers, except IE<9, there are two stages of event processing.
The event first goes down - that’s called capturing, and then bubbles up. This behavior is standartized in W3C specification.
All methods of event handling ignore the caputiring phase. Using addEventListener with last argument true is only the way to catch the event at capturing.
elem.addEventListener( type, handler, phase )
phase = true
The handler is set on the capturing phase.
phase = false
The handler is set on the bubbling phase.
For better understanding of event capturing and bubbling you can follow this link
okey, One thing you and do is use the stopPropogation() at the top in Dom.
eg. you have a table(#table1) and elements(tr,td).
so, if i do:
table1.addEventListener("click",function(event){
event.stopPropagation();
console.log(this);
},true);
tableElem[2].addEventListener("click",function(event){
console.log(this);
});
tableElem[2].addEventListener("click",function(event){
console.log("hii");
});
The event will be intercepted at top and propogation will be stopped.
stopPropogation() stops propagation irrespective of on which step event is intercepted.

Is there a way to temporarily override all click bindings on an element using jQuery?

event.preventDefault() will override default event behavior of an element. How can I temporarily override all click bindings and not just default ones?
Or is there a way to save all the click bindings so I can unbind them and use them later?
Well this is not a proper answer but a workaround. We can push the required handler on top of the stack and then used return false to stop other bindings. https://github.com/private-face/jquery.bind-first
You can use jQuery.clone(true) what this does is return data for an element. The parameter that is set to true means to also copy over all the events as well.
So if you clone the element into a variable you can bring back the old click events by simply replacing your target element with its older clone (which has the old events)
So it goes as follows:
step 1:
clone the target element using jQuery.clone(true) into a variable
step 2:
remove all click events from the target element using jQuery.off('click')
step 3:
bind your event to the target element with jQuery.on('click' function etc...)
step 4:
when you're done replace the target element with its clone (which has the old events)
Here is a JSFiddle for your viewing pleasure
(Sorry for the simpleness of the JSFiddle I mocked it up quickly and I have no example situation where I would use this.)
EDIT: I forgot to explain jQuery.clone(true)
You may catch the click before it can bubble by using
element.addEventListener(type, listener[, useCapture]);
This way you can 'catch' the click before triggering the jQuery click handler, like this (which I took from this stackoverflow question:
document.addEventListener('click', function(e) {
e.stopPropagation();
}, true);
For more information (and some IE < 9 support), see developer.mozilla
Edit: details about useCapture from Mozilla:
If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation. If not specified, useCapture defaults to false.
If you have control over all of the JS code and can bind your own handler first and all other event handlers are bound with jQuery then you can do this:
var overrideClick = false;
$("#yourElementId").click(function(e) {
if (overrideClick) {
e.stopImmediatePropagation();
// e.preventDefault(); uncomment this if you want to prevent default action too
}
});
Where some other part of your code would set overrideClick = true when needed.
Demo: http://jsfiddle.net/NCa5X/
jQuery calls handlers in the order they are bound, so you can then use event.stopImmediatePropagation() to prevent the other handlers from being called.

Event bubbling/capturing - where does it start/end?

I understand that an event has two modes -- bubbling and capturing.
When an event is set to bubble, does Javascript checks up to "document"?
When an event is set to capture, does Javascript always starts from "document"?
How does Javascript know where to stop/start?
Let's say I have the following code in my body tag.
<div id='outer'>
<div id='inner'></div>
</div>
When I set an event to #inner to bubble, does Javascript check up to document or does it stop at #outer?
From W3C Document Object Model Events
I know I'm nitpicking but it isn't javascript that handles the events you are describing, it is the DOM-engine (Document Object Model). In the browser there are bindings between the javascript and DOM engines so that events can be propagated to javascript, but it is not limited to javascript. For example MSIE has support for BASIC.
When an event is set to bubble, does Javascript checks up to "document" ?
1.2.3 "This upward propagation will continue up to and including the Document"
"Any event handler may choose to prevent further event propagation by calling the stopPropagation method of the Event interface. If any EventListener calls this method, all additional EventListeners on the current EventTarget will be triggered but bubbling will cease at that level"
When an event is set to capture, does Javascript always starts from "document"?
1.2.2 "Capture operates from the top of the tree, generally the Document,"
Event bubbling
JavaScript checks all the way up to document. If you add a listener on document and a listener on inner, both listeners fire.
Event capturing
JavaScript starts from document and goes all the way down to inner. If you add a listener on document and a listener on inner, both listeners fire.
My Findings
Turns out that the browser does some sort of smart processing so that it
a) doesn't have to loop through the entire parent hierachy
and
b) doesn't have to loop through all events.
Proof
a) It takes the browser no time to trigger both click events when the inner div is clicked:
Fiddle
b) It takes the browser no time to trigger both click events when the inner div is clicked when lots of other events exist that are attached to other DOM elements not in the parent hierachy:
Fiddle
Partial answer..
1 - When an event is set to bubble, does Javascript check up to "document" ?
Not if one of the elements in the hierarchy decides to stop the bubbling by calling stopPropagation()

How to attach multiple event handlers to addEventListener() method and what is bubbling.vs.capturing differences?

How do i attach multiple event handlers to addEventListener() method
For eg:
elem.addEventListener("mouseover",handlers....,false/true);
I also wanted to know how the bubbling when set to false and capturing when set to true on the 3rd parameter does in the dom tree.
Event bubbling means that when an event is triggered on an element, this element's parent is then checked for an event of the same time. If one exists, it is also triggered. This process is then repeated all the way up through the DOM tree. I believe that bubbling events will also make use of capturing (see below) before the bubbling process.
Capturing starts from the root and traverses the DOM tree down to the target element, triggering events of the target's type on the way.
For a better understanding of this, you can find more information here.
As for your first question, it has been a while since I worked with this, so therefore I do not remember a way to do what you want in one statement. However, you could do something like this:
myElement.addEventListener('click', myFunction1, false);
myElement.addEventListener('click', myFunction2, false);

Performing an action on Parent/Child elements independently

I have HTML similar to the following in my page
<div id="someDiv">
<img src="foo.gif" class="someImg" />
</div>
The wrapper div is set up such that when it is clicked, it's background-color changes using the following jQuery code.
$("div").click(function(event){
$(this).css("background-color", "blue");
});
I also have some jQuery associated with my img that will do some other function (for the sake of argument I am going to display and alert box) like so:
$("img[class=someImg]").click(function(event){
alert("Image clicked");
});
The issue I have come across is that when I click on the img, the event associated with the div is also triggered. I'm pretty sure that this is due to the way that jQuery (or indeed JavaScript) is handling the two DOM elements - clicking the img would require you to also technically click the div, thus triggering both events.
Two questions then really:
Is my understanding of the
DOM/JavaScript flawed in some way or
is this actually how things are
occurring?
Are there any jQuery methods that
would allow me to perform actions on
a child element without invoking
those associated with its parent?
That is known as event bubbling, you can prevent it with stopPropagation():
$("img[class=someImg]").click(function(event){
alert("Image clicked");
event.stopPropagation();
});
.
Is my understanding of the DOM/JavaScript flawed in some way or
is this actually how things are
occurring?
That is because of what is known event bubbling.
Are there any jQuery methods that would allow me to perform actions
on a child element without invoking
those associated with its parent?
Yes, you need stopPropagation()
No, this is by design. Events bubble up through the entire dom, if you put another handler on body, it would fire too
Yes :) JQuery normalizes the event object, so adding event.stopPropagation() in your img click handler will give you the behavior you expect on all browsers
The problem you just facing is called "event bubbling". That means, if you click on a nested
element, that click event will "bubble up" the DOM tree.
If other elements also are bound to an click event, their listeners will fire aswell.
Solution to prevent this is called:
stopPropagation()
which is used within your event handler
$("img[class=someImg]").click(function(event){
event.stopPropagation();
alert("Image clicked");
});
This is what's called event bubbling, and you can stop it to get the behavior you want with .stopPropagation() (or return false; if you want to stop the event completely, including handlers on the same level), like this:
$("img[class=someImg]").click(function(event){
alert("Image clicked");
event.stopPropagation();
});
You can view a demo here, comment it out and click run again to see the difference.
The short version is that when most event types happen, they happen on the immediate element, then bubble up the DOM, occurring on each parent as they go. This is not jQuery specific at all, native JavaScript does this. If you're more curious, I'd read the linked article, it has a great explanation of what's going on.

Categories

Resources