/    Sign up×
Community /Pin to ProfileBookmark

Cross-Browser Event Handling

I’m trying to augment Object.prototype with an addEvent method that will add event listeners, and will work regardless of whether the browser is IE or not.

Here’s what I have: So far it seems to work in non-IE browsers, but in IE8 it doesn’t work. Where am I going wrong?

[CODE] (function(){
try{
if(document.getElementById){
if(window.attachEvent){
Object.prototype.addEvent = function(evt,func){
this.attachEvent( (“on”+evt), func );
}
}
else if(window.addEventListener){
Object.prototype.addEvent = function(evt,func){
this.addEventListener(evt,func,false);
}
}
else{
alert(“Old.”);
}
}
}
catch(e){
console.log(e);
}
})();

window.onload = function(){
var myDiv = document.getElementById(“redBox”);
myDiv.addEvent(“mouseover”, function(){alert(“Hello!”);} );
}
//Then there’s just an HTML div with an ID of “redBox”
[/CODE]

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@Declan1991Jul 18.2010 — I really wouldn't modify object.prototype. It's not guaranteed to work, and will lead to problems. In general, prototyping any native object is hassle, full of bugs and not always working as intended.
Copy linkTweet thisAlerts:
@Dean440authorJul 18.2010 — I really wouldn't modify object.prototype. It's not guaranteed to work, and will lead to problems. In general, prototyping any native object is hassle, full of bugs and not always working as intended.[/QUOTE]

Is there another way to do this?

And what would be the difference between

[CODE]Object.prototype.method = function(){} .... and...
Object.method = function(){}[/CODE]
×

Success!

Help @Dean440 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...