Hi, I'm writing a Javascript add-on (not in jQuery) which starts working when a certain event has been triggered. It works fine on most of the sites, but I encountered problems in sites that use stopPropagation(). Is it possible to bypass this and attach the event anyway? Thanks!
How does stopPropagation()
get in your way? (Add more description how/on what your add-on works/attaches).
The only thing stopPropagation()
does, is to stop the event from bubbling up to the parent element of the element which received the event. Thus the event handlers on the parent aren't called. But multiple handlers for the same event directly on the element are all called.
So... as long as you bind your event-handler directly to the element which the event is first generated on first, you are ok. If you just try to listen for events on e.g. on body
and rely on all events bubbling up to you, you are out of luck.
e.g. if you now click on the red div you will get an alert saying sibling handler
and one saying inline handler
although the earlier defined inline-onclick
handler calls stopPropagation()
.
(Note: this sample doesn't handle IE specifics which uses attachEvent()
and cancelBubble
)
<style type="text/css" media="screen">
#parent1 { background-color: green; width:300px; height:300px }
#test { background-color: red; width:200px; height:200px }
</style>
<div id="parent1">
<div id="test" onclick="javascript:event.stopPropagation();alert('inline handler');"></div>
</div>
<script type="text/javascript">
parent1.addEventListener('click',
function(e) { alert('parent'); },
false
);
test.addEventListener('click',
function(e) { alert('sibling handler'); },
false
);
</script>
For standards-compliant browsers, use the capturing phase. For IE, you can capture mouse events by calling setCapture on an element (probably the body
). Once you've done your thing, call fireEvent on the event
object's srcElement
.