Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-Run application Javascript on ajax loaded content

I would like all AJAX loaded content in my app to be evaluated by my application JQuery script, the same as normal loaded content is. e.g. JQuery scans through the AJAX loaded content for selectors, like 'modal box links' etc.

All my JavaScript is in the normal document.ready, which works fine for normal HTTP loaded pages:

$(document).ready(function(){
  // my apps javascript
});

I would like to use something like .ajaxComplete to fire a re-run of everything contained in document.ready to evaluate newly loaded AJAX content for jquery selectors.

$(document).ajaxComplete(function(){
  // Re-run all my apps javascript
})

Is there some code I can put in .ajaxComplete to do this?

Hope this makes sense, please let me know if it doesn't, and I will edit question details.

like image 553
David Barlow Avatar asked Jan 20 '11 02:01

David Barlow


2 Answers

you could encapsulate everything in your document.ready into a function and just call that function again to re-bind

or...

a better approach would be to take advantage of the live() and delegate() jQuery methods so that all current and future elements matching those selectors will be bound to these events as well.

example using live(): http://api.jquery.com/live/

$('.clickme').live('click', function() {
    //all elements that exist now and elements added later
    //with this class have this click event attached
});

example using delegate(): http://api.jquery.com/delegate/

$("table").delegate("td", "hover", function(){
    //all current and future td elements in all current tables
    //have this hover event attached
});
like image 72
hunter Avatar answered Oct 27 '22 18:10

hunter


What you need to do is define your code in a function instead of anonymously. Anonymous functions are not reusable, but if you write a function, then that function can be bound to multiple events.

like image 43
jmort253 Avatar answered Oct 27 '22 17:10

jmort253