Wednesday, June 11, 2008

Dynamically set the onclick attribute of a html element using Javascript

I've been trying to dynamically set the onlick attribute of a span element in Javascript.
I tried a couple of things including:
var newNavNode = document.createElement("span");
newNavNode.onclick = "horizontalNavClick('"+nodeValue+"');" ;

But this wasn't working as a reference to the function was needed and not a string.

I googled and found this post: http://codingforums.com/archive/index.php?t-55356.html

And modified my script to:
var newNavNode = document.createElement("span");
newNavNode.onclick = new Function("horizontalNavClick('"+nodeValue+"')");

This worked like a charm. Thanks Willy Duitt!

Happy scripting everyone!

No comments:

Post a Comment