I'm trying to add a method to the Event prototype. In order to call/set preventDefault()
or, in IE-speak returnValue = false
and -if desired- stopPropagation()
/ cancelBubble = true;
. I thought the code below would have sufficed.
Event = Event || window.Event;
//^^ makes the fiddle work on IE8 ^^
if(!(Event.prototype.stopEvent))
{
Event.prototype.stopEvent = function(propagate)
{
"use strict";
propagate = (propagate ? true : false);
if (this.preventDefault)
{
this.preventDefault();
if (propagate === false)
{
this.stopPropagation();
}
}
else
{
this.returnValue = false;
this.cancelBubble = !propagate;
}
return this;
};
}
Which seems to work, as you can see here. This fiddle shows OK
in IE8, firefox and chrome. Though, when I add this to my script, IE8 breaks on the first line, saying 'Event is undefined'. Leaving out "use strict";
makes no difference at all.
Reluctantly, I tried this, too:
if (typeof Event === 'undefined')
{
var Event = window.Event || window.event;//FFS IE :-(
}
But to no avail: Error: 'Event.prototype' is null or not an object
, so I got 1 line further. The thing is, the entire prototype method is a copy paste from my script, but what am I overlooking here? Any idea's/suggestions?
Thanks
PS: I like Pure JavaScript, so please, don't suggest jQuery, prototypejs, dojo,... as a solution. I've just gotten rid of jQuery. (I like jQuery, but there is no need for it in this case)
Update
Things have taken a turn for the worse, I'm afraid. I found this MSDN reference. The entire page deals with DOM Element prototypes. It's pretty fair to say they are available and usable in IE8 (to some extent). On this page, this code caught my eye:
Event.prototype.stopPropagation = function ()
{
this.cancelBubble = true;
};
Event.prototype.preventDefault = function ()
{
this.returnValue = false;
};
It can be found ~3/4ths of the page down, in the section titled "Powerful Scenarios"
. This is, to my mind exactly the same thing as I want to do, but what's more: if I try this code via jsfiddle, it doesn't even work, whereas my jsfiddle (with my code) did work on IE8. This is just the last few lines of a snippet, but as far as I can work out, these few lines of code should work just fine. I've altered them as follows:
Event.prototype.stopPropagation = function ()
{
if (this.stopPropagation)
{
return this.stopPropagation();
}
this.cancelBubble = true;
};
Event.prototype.preventDefault = function ()
{
if (this.preventDefault)
{
return this.preventDefault();
}
this.returnValue = false;
};