Entry
How can I dynamically set the onclick of a link to dynamically generated code?
Jan 9th, 2002 06:37
David Blackledge, Russ Locke,
> I've been trying to accomplish this task with a function like such:
>
> function setNextClick(nextHref) {
> document.getElementById('nextlink').onclick =
> "top.bodyframe.location.href="+nextHref+";return false;";
> }
>
> But this is not working... when I click on the link, nothing happens.
> I've compared the preset onclick with the new setting using an alert
> to display the element's onclick attribute, and the only difference is
> the preset onclick returns a function declaration around the given
> code.
>
> "function anonymous() {" ... the onclick code ... "}"
>
> I've tried adding that text in with my new code and still have had no
> luck.
>
> Any suggestions??
When you specify an onclick (or any other event handler) in-line in the
HTML tag, you are actually defining the body of a function. Notably, in
Netscape (and the latest DOM-compliant browsers) this function actually
has one parameter passed to it containing the event information, but
since you're not naming it when defining the function in-line, you
cannot access it.
To set an event handler from JavaScript, you first have to define the
function yourself, then set the handler to that function object. You
can define a function in two ways:
function myOnClick(e) {
... the onclick code ...
}
or
var myOnClick = new Function("e", "...the onclick code...");
In this case, the second is desireable since you are defining the
function dynamically. The "e" is the parameter mentioned above that
contains the event information.
You then assign the event handler with the function using (based on the
above code):
document.getElementById('nextlink').onclick = myOnClick;
Be sure not to include parentheses () after the function name or you
will be assigning the return value after executing the function to the
handler, rather than assigning the function itself.
David.
http://David.Blackledge.com