faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 133 people (2%) answered Yes
Recently 3 of 10 people (30%) answered Yes

Entry

How do I prevent event cascading?

Jan 13th, 2003 17:03
Gavin McLeod, Russ Locke,


Old example deleted.......
Working example is listed below...
use a global nobubble variable to control the event bubbling.... this 
will work in any browser and in any version. IE has some event bubbling 
internals which can be set... however using a nobubble variable will 
allow you more flexability as you build this out.
<html>
<head>
<script>
var nobubble = false;
function some_func(id) {
  if (!nobubble) {
    nobubble = true;
    alert(id);
  }
}
</script>
</head>
<body>
<ul>
  <li>...</li>
  <li>
    <ul onMouseOver="nobubble = false;" onClick="some_func
(this.id);return false;" id="this_id">
      <li>...</li>
      <li>...</li>
        <ul onMouseOver="nobubble = false;" onClick="some_func
(this.id);return false;" id="another_id">
          <li>...</li>
          <li>...</li>
          ....
        </ul>
      </li>
      ....
    </ul>
  <li>
    <ul onMouseOver="nobubble = false;" onClick="some_func
(this.id);return false;" id="whatever_id">
      <li>...</li>
      <li>...</li>
      ....
    </ul>
  </li>
   ...
</ul>
</body>
</html>
()()()()())()()()()()()()()()()()()()()()()()()()
Thanks for the "nobubble" suggestion, but that didn't work too well.  
It turns out that by clicking on an internal UL the user is also, 
simultaneously, clicking on the outer UL and two different onClick 
events are fired in sequence, which is also true of the onMoseOver 
event.
The data that is populating the page is XML and XSL driven and the 
inner ULs are built using a recursive XSL template, so it was 
impossible to get around the prob without some other significant 
changes.
I eventually solved it by doing two things:  
1) get away from the list construct and use a series of CSS styled DIV 
elements.  This still left DIVs contained by DIVS, but things get 
somewhat easier.
2) write another js function that walks the DOM tree to selectively act 
as appropriate.  This solution is geared to the particular prob and 
might not be sufficiently generalized for broader contexts.
This was quite a learning experience!