I am trying to prevent JavaScript events from continuing to propagate, using YUI. The following is some minimal HTML and some minimal JavaScript which demonstrates the problem:
HTML:
<a href="#foo" onClick="fooClickTest()" id="foo">foo</a>
<a href="#bar" id="bar">bar</a>
JavaScript:
function fooClickTest(e) {
alert('fooClickTest');
YAHOO.util.Event.addListener('bar', 'click', barClickTest1);
YAHOO.util.Event.addListener('bar', 'click', barClickTest2);
YAHOO.util.Event.addListener('bar', 'click', barClickTest3);
YAHOO.util.Event.preventDefault(e);
}
function barClickTest1(e) {
alert('barClickTest1');
YAHOO.util.Event.preventDefault(e);
}
function barClickTest2(e) {
alert('barClickTest2');
YAHOO.util.Event.preventDefault(e);
YAHOO.util.Event.stopEvent(e);
// Also tried:
// YAHOO.util.Event.stopPropagation(e);
// and:
// if (e.stopPropagation) {
// e.stopPropagation();
// } else {
// e.cancelBubble = true;
// }
}
What I expect to happen is that the user can click on 'foo' to add the three click handlers, and then click on 'bar'. Then, the user will see TWO alerts, 'barClickTest1' and 'barClickTest2'. Instead, all three alerts occur. The YAHOO.util.Event.stopEvent(e) does not do what I expect, which is to stop the event propagating out to barClickTest3.
I have tested my code in Firefox 3.0.7 and in Safari 3.2.1. As you can see above, I have also tried YAHOO.util.Event.stopPropagation(e) and e.stopPropagation(). None of them did the trick.
This is obviously a contrived example, though it does demonstrate the problem. In the real solution, I will only prevent event propagation if some conditions are met.
Is my understanding of JavaScript's events simply messed up? How do I accomplish my goals?