I have a site which loads content through AJAX. I need to attach onclick handler to some div which was dynamically loaded. It works fine if my event handler is already defined in my main javascript file (whether I attach it through markup via attribute onclick="myFunc"
on by more pedantic addEventListener
).
However, I would like this event handler to be defined in a <script>
tag of the dynamically loaded content. Then it doesn't work, whether <script>function myHandler(){}</script>
is before or after the <div onclick='myHandler();'>
.
I tried to attach it at the end of the XmlHttpRequest:
contentDiv.innerHTML = xhr.responseText;
var handlerName = getItFrom(xhr.responseText);
var clickFn = window[handlerName];
loadedDiv.addEventListener('click', clickFn);
Doesn't work neither: handlerName
is correct, but clickFn
remains undefined...
I prefer a pure js answer but jquery is ok if I can easily translate it.