Often in the course of developing a piece of code we will need to observe the flow of an event as it goes through the DOM hierarchy. We will have handlers on elements that will catch the event when it is fired from an element. Once this has happened the event gets passed further up the DOM tree, which means that parent elements have a chance to process the event. So for example when you have two divs inside a webpage. One div is inside the other div like:
<div id="firstDiv"> This is an outer div text. <div id="secondDiv"> This is an inner div text. </div> </div>
Now we can add a handler to each div tag. These handlers will simply create an alert letting us know which element was called.
$('div').click(function(){ alert( $(this).attr('id')); });
So now when we click on the text: This is an outer div text, we get the alert firstDiv. Now the important point is what happens when you click the inner div text: This is an inner div text, which when clicked generates two alerts firstDiv and secondDiv. This is an example of event propagation. You can see the outer div tag only had its alert shown, but the event propagated out of the inner div tag to the outer div tag and had the inner and outer alerts. This is the result of having an event handler associated to the div's parent element. If this outer div was inside another element it would continue to porpagate up the DOM hierarchy until no more parents were available.
Occasionally you don't want an event to propagate past a certain element. In this case a common techinique you will see is just to return false from the event handler, however you can also use the stopPropagation method which as the name describes prevents the event from propagating futher up the DOM heirarchy.
No comments:
Post a Comment