JavaScript event bubbling and event delegation

Source: Internet
Author: User

JavaScript event bubbling and event delegation

Jiang Jianyu-2 reviews

It's not too much to learn before you touch JavaScript. Light rain is the habit of the usual learning to share things out. On the one hand to strengthen their impressions, on the one hand can let their experience for others to answer questions. We know that JavaScript can monitor the various events of elements on a page, such as clicks, mouse moves, moves, element changes, and more. This time, let's talk about event bubbling and a more cool application, event delegation. Without special instructions, the following are performed within the jquery framework.

Event bubbling

What is "event bubbling"? Suppose there is a glass of water, and the water is divided into layers of different colors in some magical way. At this point, a bubble emerges from the bottom, and the bubbles rise to the top of the layer. And you can see and capture this bubble no matter which layer of water you are observing. OK, change "water" to "DOM" and Change "bubble" to "event". This is "event bubbling".

In order to be able to visually observe this phenomenon, I wrote a small program. This page has a total of 4 nested squares. The biggest one is at the top, the smallest one at the bottom. I've bound a single click event for each layer, and when that layer is clicked, it will be painted for that layer. Try, what happens when you click on the smallest square? What happens when you click the other? (Click here to view demo)

Css
. White{Background-color:#fff;}#d1{Width:400px;Height:400px;Border:1px solid#000;Margin:50px50px;}#d2{Width:300px;Height:300px;Border:1px solid#000;Margin:50px50px;}#d3{Width:200px;Height:200px;Border:1px solid#000;Margin:50px50px;}  #d4 { Width:100px;height:100px; border:1px solid  #000 ; Margin:50px 50px             /span>            
Html
<div id="d1" class="white">    <div id="d2" class="white">        <div id="d3" class="white">            <div id="d4" class="white"></div>        </div>    </div></div><button id="reset1">重置</button>
Javascript
Jquery(' #d4 ').Click(function(){Jquery(This).Css(' Background-color ',' Yellow ')});Jquery(' #d3 ').Click(function(){Jquery(This).Css(' Background-color ',' Green ')});Jquery(' #d2 ').Click(function(){Jquery(This).Css(' Background-color ',' Blue ')});Jquery(' #d1 ').Click(function(){Jquery(This).Css(' Background-color ',' Red ')});Jquery ( ' #reset1 ' click (function ({jquery (. Css ( ' Background-color '  ' #fff ' ) }     

Yes, click on the smallest one, and all the outside will be colored. You will find that by clicking on the inner square, all the squares in the outer layer will be colored. Because they also capture the Click event. Look, they've got the bubbles!

Event delegate

Example of the previous section we made a little bit of a change. The bubbles carry a message that tells them what layer they are producing at each level. JavaScript events do take this property. When the program captures an event, it knows which element on the page the event came from. Modify the program above and use event delegates to handle click events. When capturing a click event at the topmost level, see which layer the event originated from and then paint only that layer. Click each layer again to see the actual effect. Only the square of the current click is discolored, and nothing else is responding. (Click here to view demo)

Jquery(' #d1 ').Click(function(E){var t=Jquery(E. Target);var ID= T.attr(' ID ');If(ID===' D4 '){T.Css(' Background-color ',' Yellow ');}ElseIf(ID===' D3 '){T.Css(' Background-color ',' Green ');}ElseIf(ID===' D2 '){t. Css ( ' Background-color '  ' Blue '  else {tcss ( ' Background-color '  ' red ' ) ; }})               

Of course, if you have a nested page element that uses an event delegate and delegates to the topmost level, you need to be aware that if one of the elements you don't want its events to bubble, you can use some way to block the bubbling of the event. In the jquery framework, you can use the Stoppropagation () method to implement without worrying about browser compatibility.

$(' #bind ').Click(function(){If($(This).Is(': Checked ')){ $(' #d4 ').Bind(' Click ',function(E){E.Stoppropagation();alert ( ' bubbles are blocked, this block will not change color ' })  else {$ ( ' #d4 ' unbind ( ' click ' }})               

After resetting, select "Block event bubbling from the smallest block" and click on the smallest square to see if it changes color. Obviously does not change color, prevents bubbling, the parent layer will not be able to receive the Click event.

Precautions

Event delegation is an application of event bubbling that reduces the number of binding elements and does not have to worry about the need to re-bind the child nodes after they are replaced. Because the capture of the event and subsequent execution of the code has been fully delegated to its parent node. If a page contains a large number of elements that require binding events, doing so reduces the number of event bindings and offloads the browser, which will undoubtedly improve page performance.

But there are some things to be aware of. If the node used to capture the event will return false in some cases, and one of your click events is not delegated to the parent, then you may need to block the node's event bubbling to achieve the correct purpose. For example: I have some buttons and other elements inside a div. Use event delegates to handle the clicks of these buttons, or return False if not the button. At this point, the error arises. If the other elements contain links, then the linked click events are also delegated to the Div. However, clicking on the link will not have any reaction. The workaround is to handle the link in the delegated code, and to prevent the linked event from bubbling.

Reprint: http://www.pureweber.com/article/event-delegation/

JavaScript event bubbling and event delegation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.