/    Sign up×
Community /Pin to ProfileBookmark

eventhandler on node

I would like to create the following

[CODE]
fnTest(sId,sTxt) {
alert(sId + ‘: ‘ + sTxt);
}

<a href=”#” id=”i23″ onClick=”fnTest(this.id,’Iiyama ProLite E511S’)”>E511S</a>[/CODE]

If you write it all out in HTML this works fine. I need to create this dynamically, which works fine up to the definition of de onClick event handler:

[CODE]
var eA = doc.createElement(“a”);
eA.setAttribute(“id”,”d23″);
eA.setAttribute(“href”,”#”);
eA.setAttribute(“onClick”,”fnTest(this.id,’Iiyama ProLite E511S’)”);[/CODE]

FF executes the code, IE does nothing (but also no error). Another approach would be to attach an eventHandler to the element. I used Nicholas C. Zakas’ code and changed the function:

[CODE]
fnTest() {
alert(‘Testing 123′);
}

var EventUtil = new Object;
EventUtil.addEventHandler = function (oTarget, sEventType, fnHandler) {
if (oTarget.addEventListener) { // DOM
oTarget.addEventListener(sEventType, fnHandler, false);
}
else if (oTarget.attachEvent) { //IE
oTarget.attachEvent(“on”+sEventType, fnHandler);
}
else { // ? what else is there ?
oTarget[“on”+sEventType] = fnHandler;
}
};

var eA = doc.createElement(“a”);
eA.setAttribute(“id”,”d23″);
eA.setAttribute(“href”,”#”);
EventUtil.addEventHandler(eA,’click’,fnTest);[/CODE]

Executes in both browsers, but now I am unable to pass parameters. So I changed the function to:

[CODE]
fnTest() {
alert(this.id);
}[/CODE]

FF executes OK, IE7 comes with a box that says: “undefined”.

I see at least one last alternative: innerHTML. I have never worked with it and since it is not a DOM standard, I’d rather not use it. If it can make things work I’ll use it, but only if nothing else can.

Anyone any ideas?

Thanks,Erik.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@FangMar 31.2007 — eA.onclick=function(){fnTest(this.id,'Iiyama ProLite E511S');};
Copy linkTweet thisAlerts:
@rauzerauthorMar 31.2007 — Yes, that's it. And I can keep using my libraries.

Thanks!
Copy linkTweet thisAlerts:
@rauzerauthorMar 31.2007 — Thanks, Fang. It not only works, but I can keep using my libraries also.

Thanks!
×

Success!

Help @rauzer 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.2,
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: @meenaratha,
tipped: article
amount: 1000 SATS,

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

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