I'm creating html on runtime like this:
var myVar = "<div id='abc'>some clickable text</div>"
Now, I want to attach some event, say onclick, to this div. How can I do that on next line? I'll add this to DOM later.
PS: I've to accomplish this without using JQuery.
Try building the div as a DOM element first.
The addEventListener method is standard, but not every browser plays nice with the standard.
EDIT: As mentioned, an element must be added to the DOM first.
Brian Glaz is totally right but, if for some reason, you really need to do it this way, you have two options:
you can only add events to something that is already in the DOM, using pure javascript, so you would have to include it in the html like:
and then, attach the event with
With jQuery, you could use .live() to attach events to elements that are not yet present in the DOM:
so you could add the div later...
Will this help? Since you dynamically generate it, you know the control id of the DIV.
Or you can use this technique: attach event to the
document.body
. Then if the event target is not the needed div than just do nothing. It is the same techinque jquery uses for itslive
function:Here is demo.
Instead of building your div as a string, you'll want to use document.createElement('div'). This way you will have a real dom object, and can get and set it's propeties, including
onClick