[thelist] DOM - adding a function to a dynamically added element...
Phil Turmel
philip at turmel.org
Mon Apr 25 18:33:11 CDT 2005
Tom Dell'Aringa wrote:
> Hi there, I'm rusty and have forgotten the best way to do this.
>
> I'm adding a link inside a DIV dynamically on my page using the DOM. This link needs to have a
> function tied to the onclick event handler. If I remember correctly, you cannot do this using
> .setAttribute - because IE doesn't like it (based on my tests, that is what is happening)
>
> I had thought then you added it using the property of the object:
>
> myLink.onclick = functionName; ( with or without the brackets?)
>
> But this doesn't seem to work. My problem is compounded by the fact that I want the link to return
> false: The link should be this:
>
> <a href="" onclick="toggleHelp();return false">Page Help</a>
>
> Do I have to write this as an anonymous(?) function like:
>
> myLink.onclick = function { statements here }
>
> I'm rusty on this stuff it has been awhile, I can't remember the correct way. I also don't see a
> way to add the return false, or maybe 'return toggleHelp()' then return false in the
> function...still how would I add the return? I need to call this function from this link...
>
> Thanks
>
> Tom
Pretty close... the function's return value takes care of your problem.
Try one of these:
myLink.onclick = function (e) { statement; statement; return false; };
OR,
function functionName (e) {
statement;
statement;
return false;
}
myLink.onclick = functionName;
Note the (e) in the function definitions... that gives you access to the
event properties during the event.
For a thorough treatment:
http://www.quirksmode.org/js/introevents.html
HTH,
Phil
More information about the thelist
mailing list