Forum Moderators: open

Message Too Old, No Replies

attribute an "onClick" event to a javascript-created <div>?

         

Josefu

10:05 am on Apr 16, 2009 (gmt 0)

10+ Year Member



Hello,

I can't seem to find a means of attributing an "onClick" event (calling a function) to a javascript-created <div>. Is this possible, or does the onclick event have to be hard-coded into an already existing div?

Thanks.

daveVk

11:28 am on Apr 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



var el = document.getElementById ... // div in question
el.onclick = function(event) {...} // inline declaration
or
el.onclick = doClick; // existing, function doClick(event){...}

note. onclick, lowercase and RHS is function rather than quoted statement as per html.

Josefu

2:39 pm on Apr 16, 2009 (gmt 0)

10+ Year Member



Thank you!

also:

el.onclick = function("doClick(action)");

...seems to work.

Fotiman

4:27 pm on Apr 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



No,

el.onclick = function("doClick(action)");

does not work. Nor should it. Did you perhaps mean this:

el.onclick = Function("doClick(action)");

Remember, JavaScript is case sensitive.

astupidname

11:27 pm on Apr 16, 2009 (gmt 0)

10+ Year Member



No,
el.onclick = function("doClick(action)");

does not work. Nor should it. Did you perhaps mean this:

el.onclick = Function("doClick(action)");

Remember, JavaScript is case sensitive.


And, do not get in the habit of doing the latter either.
el.onclick = Function("doClick(action)"); has to start up the string compiler to process that into a new Function object, whereas the following doesn't:
Should be:
el.onclick = function() { doClick(action); }; //assuming ' action ' is a variable defined somewhere's

Josefu

9:19 am on Apr 23, 2009 (gmt 0)

10+ Year Member



Thank you guys - will give it a try today. Cheers!