Wednesday, July 18, 2012

Playing Around With JavaScript's stopPropagation and preventDefault Methods

While playing around with pure JavaScript events lately I created this jsfiddle to demonstrate the concepts of the event methods preventDefault() and stopPrpagation().  While you are playing with it make sure to have your Browser's console open so you can see the debugging output.

The preventDefault() method on an event, does exactly that, prevents the event's default behavior.  In this instance it stops an <a> element from going to the link.  The stopPropagation() method stops the event from bubbling up DOM nodes.  In this case we have an <a> link nested in a <span> that is nested in a <div>.  When a user clicks on the <a> the event is triggered on that element, then the span, then the div, all the way up the DOM until it reaches the document node.  Calling stopPropagation() on the <a>'s click event only triggers the event on the <a> element  and none of its parent nodes.  

Fork me on GitHub