Running javascript when adding it to html page

I have content on a web page that is simultaneously sent from the server on page load and is frequently updated via AJAX. When it is loaded initally, I use $ (function () {}) to bind and update based on news from the server. I also want to be able to run the code when it is populated, specifically to re-check for click events and update news from the server.

Is there a way to do this without doing $ .getScript separatley? I am somewhat confused about how javascript works when filling the screen via AJAX ($ ('el'). Html (...)) because I often use this with javascript enabled and it works. Can anyone figure out how this works?

+1


a source to share


2 answers


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

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



See this example .

+2


a source


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

However, jQuery 1.3 does not support blur, focus, mouse, mouse, change, and dispatch of 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 can use the liveQuery plugin .

+2


a source







All Articles