spitfire109
spitfire109

Reputation: 10039

How to call JavaScript on elements loaded with Ajax

I have some functionality that I want to work when the document is ready and also after Ajax is called, as new items are loaded into the page that need to be selected.

I can accomplish this by doing this:

var ready;
ready = function(){
  //my code here
};

$(document).ready(ready)
$(document).ajaxComplete(ready)

But that causes an issue where each Ajax call seems to add another time for the function to run. After the first AjaxComplete call, it runs once, then twice, then three times, etc.

How do I elegantly get all the code to run how I want it just once at any point while the user is on the page?

It is a Ruby on Rails app, btw.

Thank you very much.

Upvotes: 1

Views: 243

Answers (1)

asifrc
asifrc

Reputation: 5841

You're looking for jQuery's .delegate function. What is does is it binds to a parent element, and whenever an event is fired inside of it, it checks to see if the child element producing the event matches the selector you provided; if it does, it'll fire the handler. For instance the folowing example from jQuery's docs causes a click on all existing and future tds within a table to toggle the "chosen" class:

$( "table" ).delegate( "td", "click", function() {
  $( this ).toggleClass( "chosen" );
});

So if you add a new row to a table, clicking on it will toggle "chosen" even though the row didn't exist when you called delegate.

Let me know if this makes sense or if you have any questions :)

Upvotes: 2

Related Questions