Monday, May 20, 2024
163
rated 0 times [  169] [ 6]  / answers: 1 / hits: 24393  / 11 Years ago, tue, july 16, 2013, 12:00:00

I am reading a book called Adaptive Web Design by Aaron Gustafson were I got a piece of javascript that I didnt understand. While researching I find out about the difference between returning false and e.preventDefault. I also now know a little bit about the bubbeling effect of JavaScript and came to understand that to stop the bubbeling you can use e.stopPropagation() (in none-ie browser atleast).



I was playing around in fiddle but I couldnt get it working. I think it might got to do with the way the bubbeling takes effect (from root to the element and back?).



document.body.onclick = function (e) {
alert(Fired a onclick event!);
e.preventDefault();
if ('bubbles' in e) { // all browsers except IE before version 9
if (e.bubbles) {
e.stopPropagation();
alert(The propagation of the event is stopped.);
} else {
alert(The event cannot propagate up the DOM hierarchy.);
}
} else { // Internet Explorer before version 9
// always cancel bubbling
e.cancelBubble = true;
alert(The propagation of the event is stopped.);
}
}


Here is the fiddle: http://jsfiddle.net/MekZii/pmekd/ (FIXED link)
EDIT:
I copy-pasted the wrong link! Its fixed now!



So what I would like to see is that when you click on the anchor, the onclick that is used on the div doesn't get executed (this is not a practical case, just a study case!)


More From » event-bubbling

 Answers
7

Ok, I found out that my first fiddle is wrong. I found another example that does work and shows how the stopPropagation() work:



var divs = document.getElementsByTagName('div');

for(var i=0; i<divs.length; i++) {
divs[i].onclick = function( e ) {
e = e || window.event;
var target = e.target || e.srcElement;

//e.stopPropagation ? e.stopPropagation() : ( e.cancelBubble = true );
if ('bubbles' in e) { // all browsers except IE before version 9
if (e.bubbles) {
e.stopPropagation();
alert(The propagation of the event is stopped.);
} else {
alert(The event cannot propagate up the DOM hierarchy.);
}
} else { // Internet Explorer before version 9
// always cancel bubbling
e.cancelBubble = true;
alert(The propagation of the event is stopped.);
}

this.style.backgroundColor = 'yellow';

alert(target = + target.className + , this= + this.className );

this.style.backgroundColor = '';
}
}


http://jsfiddle.net/MekZii/wNGSx/2/



The example is found at the following link with some reading material:
http://javascript.info/tutorial/bubbling-and-capturing


[#76962] Monday, July 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
christianu

Total Points: 481
Total Questions: 124
Total Answers: 99

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
christianu questions
;