Welcome to WebmasterWorld Guest from 100.26.182.28

Forum Moderators: open

Message Too Old, No Replies

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

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

Preferred Member

10+ Year Member

joined:July 28, 2003
posts: 468
votes: 0


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.

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

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


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.

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

Preferred Member

10+ Year Member

joined:July 28, 2003
posts:468
votes: 0


Thank you!

also:

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

...seems to work.

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

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts:5021
votes: 26


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.

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

Preferred Member

10+ Year Member

joined:Aug 18, 2008
posts:408
votes: 0


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
9:19 am on Apr 23, 2009 (gmt 0)

Preferred Member

10+ Year Member

joined:July 28, 2003
posts:468
votes: 0


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

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members