views:

67

answers:

2

I have content on a webpage which is both sent from the server at page load, and updated frequently via AJAX. When it is loaded initally, I use $( function () {} ) to do binding and updating based on the news from the server. I want to be able to also run the code when it is repopulated, in particular to rebind click events and update with news from the server.

Is there any way to do this without doing a $.getScript separatley? I am somewhat confused on how running javascript applies when populating the screen via AJAX ( $('el').html( ... ) ) Because I often use this with included javascript and it works. Could anybody clear up how this works?

+1  A: 

Bind events on newly added DOM nodes (Ajax or otherwise) using live.

Your included scripts will run when you add them to the DOM.

See this example.

altCognito
$.live() is not rebinding anything, it's a global window listener that only binds itself once when instantiated.
duckyflip
I'm not sure if you're taking issue "re" portion of that, but it does what he's asking, which is to bind events to elements that need the events. "Re" binding is inaccurate, so I'll take it off.
altCognito
+2  A: 

With jQuery events if you want the event to apply to new elements you would use the .live() method.

However jQuery 1.3 doesn't support blur, focus, mouseenter, mouseleave, change, and submit events as live events. (change, submit, and blur/focus are on the roadmap for jQuery 1.4)

If you want to bind to any of the events not supported by .live() you could use the liveQuery plugin.

Sam Hasler