Jquery Events dont work after ajax/innerHtml
Question
i have many events such as
$('.hidefile').click(function (event) {
On page load and on certain conditions i use ajax to get the html for a certain div and fill it in with .html(htmlstring). It took me forever but i notice that the events do not work when i do this. How do i fill the div with html and have the jquery events work with it?
Solution
Bind your click events (or otherwise) to your elements using live
:
$('.hidefile').live("click", function (event) {...
When you replace elements using ajax, they lose their event handlers. You can either explicitly rebind them within the success
callback of the particular ajax method you have used to replace those elements, or use live handlers instead, which will:
Attach a handler to the event for all elements which match the current selector, now or in the future.
OTHER TIPS
How are you attaching the click event. You should do that inside the document.ready event to make sure that the DOM has been loaded. Also, as suggested by karim79 you should use the live function to make sure that the events persists.