Binding Javascript Event Handlers to a an Ajax HTML Response?
Posted
by John
on Stack Overflow
See other posts from Stack Overflow
or by John
Published on 2010-04-25T14:13:07Z
Indexed on
2010/04/25
14:23 UTC
Read the original article
Hit count: 153
AJAX
|javascript-events
Let's say I have the following HTML code
<div id="outer">
<div id="inner">Hello World</div>
</div>
At the end of my HTML page, I use javascript to attach event handlers like so,
document.getElementById('inner').onclick = function() {alert(this.innerHTML);}
document.getElementById('outer').onclick = function() {
/* An Ajax Call where the response, which will be a string of HTML content, then goes into document.getElementById('outer').innerHTML */
document.getElementById('inner').onclick = function() {alert(this.innerHTML);}
}
In the above code, I am expecting <div id="inner">Hello World 2</div>
to come back which requires me to re-attach the onclick event handler. This makes sense because the new response coming back is just a string, and I have to tell the browser that after converting to DOM, i also need some event handlers
So my question is, is there a better way to manage event handlers on AJAX response that contains HTML content? I could use inline javascript within the html response, but then it prevents me from achieving non-intrusive javascript. So is there a way to achieve non-intrusive javascript and an efficient way to "maintain" event handlers of ajax html responses?
© Stack Overflow or respective owner