/    Sign up×
Community /Pin to ProfileBookmark

Listeners not working with onclick

I’ve decided it’s time I made my site more accessible. I’m trying to get rid of all inline onclick handlers and place them in an external file. I’ve search around and found the following code from AListApart, which works with onclick. I tried to modify it for mouseovers but Firebug just reports an exception.

[CODE]
// http://www.alistapart.com/articles/popuplinks
function listen(event, elem, func) {
elem = getElem(elem);
if (elem.addEventListener) // W3C DOM
elem.addEventListener(event,func,false);
else if (elem.attachEvent) // IE DOM
elem.attachEvent(‘on’+event, function(){ func(new W3CDOM_Event(elem)) } );
// for IE we use a wrapper function that passes in a simplified faux Event object.
else throw ‘cannot add event listener’;
}
function W3CDOM_Event(currentTarget) {
this.currentTarget = currentTarget;
this.preventDefault = function() { window.event.returnValue = false }
return this;
}
function getElem(elem) {
if (document.getElementById) {
if (typeof elem == “string”) {
elem = document.getElementById(elem);
if (elem===null) throw ‘cannot get element: element does not exist’;
} else if (typeof elem != “object”) {
throw ‘cannot get element: invalid datatype’;
}
} else throw ‘cannot get element: unsupported DOM’;
return elem;
}
[/CODE]

The in the head:

[CODE]
listen(‘load’, window, function() {
listen(‘mouseover’,’trigger1′,function1);
listen(‘mouseover’,’trigger2′,function2);
});
[/CODE]

Is there any way I can use onclicks which aren’t inline?

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@felgallOct 20.2007 — listen('mouseover',document.getElementById('trigger1'),function1);
Copy linkTweet thisAlerts:
@EchilonauthorOct 21.2007 — Still the same error I'm afraid. Is there another method you know of?
Copy linkTweet thisAlerts:
@Declan1991Oct 21.2007 — I normally use
[code=php]document.getElementById("id").onmouseover = new Function('alert("");');[/code]
or the Universal Event Model.
×

Success!

Help @Echilon 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 5.28,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

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

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...