I understand the proper way to handle event.stopPropagation for IE is
if(event.stopPropagation) {
event.stopPropagation();
} else {
event.returnValue = f
If you're doing your own event handling in plain javascript, then you probably already have a cross browser routine for setting event handlers. You can put the abstraction in that function. Here's one that I use that mimics the jQuery functionality (if the event handler returns false
, then both stopPropagation()
and preventDefault()
are triggered. You can obviously modify it however you want it to behave:
// refined add event cross browser
function addEvent(elem, event, fn) {
// allow the passing of an element id string instead of the DOM elem
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// normalize the target of the event
window.event.target = window.event.srcElement;
// make sure the event is passed to the fn also so that works the same too
// set the this pointer same as addEventListener when fn is called
var ret = fn.call(elem, window.event);
// support an optional return false to be cancel propagation and prevent default handling
// like jQuery does
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
Or, you can just make a utility function like this:
function stopPropagation(e) {
if(e.stopPropagation) {
e.stopPropagation();
} else {
e.returnValue = false;
}
}
And just call that function instead of operating on the event in each function.
Probably this:
Event = Event || window.Event;
Event.prototype.stopPropagation = Event.prototype.stopPropagation || function() {
this.cancelBubble = true;
}
returnValue = false
is an analogue for preventDefault:
Event.prototype.preventDefault = Event.prototype.preventDefault || function () {
this.returnValue = false;
}
We can use this alone: event.cancelBubble = true
.
Tested working in all browsers.