1

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?

1
  • I think if you used a javascript framework like jQuery, they have this sorted out via the .live() functionality, unless you want to roll up one of your own Commented Apr 25, 2010 at 14:19

2 Answers 2

2

You can use something like jQuery live. It lets you bind an event handler to elements that match a selector now and in the future.

Sign up to request clarification or add additional context in comments.

1 Comment

Be aware that .live() is deprecated as of 1.7
2

Ben Nolan made a nice framework once called "Behaviour". He has since abandoned it, but the idea is still sound. The idea was to put your event handlers into "sheets" (just javascript objects) under properties named using CSS selectors.

You could use an object such as this:

{
    '#inner': function() { ... }
}

A general function could iterate the properties of such an object when necessary to reapply event handlers.

I have an old copy of Behaviour stored here: http://www.kruse-net.dk/javascript/lib/behaviour-1.2.js that you're free to draw inspiration from or use.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.