Hi.
How do I add a click event using addEventListener (window.onload) when the tags in question are being generated from the server (via an xmphttp request, no less)?
Thanks!
Hi.
How do I add a click event using addEventListener (window.onload) when the tags in question are being generated from the server (via an xmphttp request, no less)?
Thanks!
You have to apply the event hanlders after the elements have been inserted into the DOM
You can try to handle events for parent elements, which are available as DOM loaded, then get element related to event.
<ul id="list">
<li id="first">The first</li>
<li id="second">The second</li>
<li id="third">The third</li>
</ul>
document.getElementById('list').onclick(function(e){
o = e.originalTarget;
// if you click on second li o will bi the same as document.getElementById('first')
// even if li with id "first" is inserted to DOM after creating this event handler to "list"
// so here you can perform actions with it
// hope it will help
});
Thanks all.
I solved this by adding the below code to the "on success" event of the XMLHTTP request that populated the DOM with the elements coming from the server. That worked for me. Josh, you got my head moving in the right direction (although it would have been nice to see a code illustration) so I marked your response as the answer.
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
var m_sel=document.getElementById("fcat");
if (m_sel) {
var maxi = m_sel.options.length;
for( var i = 0; i < maxi; i++ )
{
var option = m_sel.options[i];
option.addEventListener( "click", toggleElem, true );
}
}
}