Prevent the spread of events with jQuery

Two overlapping elements of the HTML DOM, both sensitive to an event click , suffer the age-old problem of the propagation degi events between the layers of the DOM itself: the so-called event bubbling. This behavior (which is also found in other development environments: See Actionscript 3.0: MovieClip MovieClip over ) is in itself useful in many cases. However, in others, it creates many problems. . For example, imagine you have a div container-sensitive event click . Superimposed on this are a classic anchor link a . Clicking on the link in addition to the "page turn" triggered the event associated with the div container. contenitore, possiamo usare jQuery in questo modo: To prevent the spread dall'anchor click event a the div container, we can use jQuery like this:

1
2
3
4
5
6
7
8
9
10
11
"box" > < div id = "box">
"mylink" href = "#" > Link < / a > < a id = "MyLink" href = "#"> Link </ a >
</ div >

<! - Or ->

"box" > < div id = "box">
<! - Content ->
</ div >
<! - This anchor has styles set so as to be in absolute or relative position and then superimposed on the container div ->
"mylink" href = "#" > Link < / a > < a id = "MyLink" href = "#"> Link </ a >

si propaghi agli elementi sottostanti: Using jQuery you can prevent the event click on the anchor tag a be propagated to the items mentioned below:

1
2
3
4
5
6
7
) . click ( $ ('A # MyLink'). Click (
event ) { function (event) {
event. target . href ; document. location = event. target. href;
; event. stopPropagation ();
; event. preventDefault ();
}
);

One Response to "Prevent the spread of events with jQuery"

  1. October 7, 2009 Matthew:

    Hello,

    someone tells me that the code works in the post? I would keep the links of the first layer of my multi-level menus do open a new page (I create the menu with the functions of WordPress, so I can not remove the links), ie: clicking on the link should only appear the first level submenu ( I do appear with jqueryslidemenu, but that's another story ... :) )
    Thank you!

Leave a comment

XHTML TAG PERMIT: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL