mmcglynn
mmcglynn

Reputation: 7672

Running JQuery scripts on AJAX loaded content

I am using .load() to pull static HTML files onto my main HTML page. The scripts and selectors that I have written exist within:

$(document).ready(function(){});

But they don't work on the AJAX loaded content. I have read that this is because the selectors that I am using are not available.

Is there a better way to do this? Adding the script to the window.load function doesn't work either:

$(window).load(function() {});

Upvotes: 23

Views: 28722

Answers (4)

Adam Kiss
Adam Kiss

Reputation: 11859

There are more than one option:

  1. you can add initialization scripts [ $(this).click... ] into callback function of $.load()
  2. you can use $.live(), which creates handlers even for dynamically loaded/created objects.

More here:
callback: http://api.jquery.com/load/ (notice the "complete()" function)
bind: http://api.jquery.com/live/

Edit: My mistake, it was live(), not bind(), thank you guys

Upvotes: 3

Scott Evernden
Scott Evernden

Reputation: 39986

jQuery load takes an optional callback function argument which you could use to do any setup you need AFTER your ajax-ed content is loaded

Upvotes: 0

Jman
Jman

Reputation: 936

$(document).ajaxComplete(function(){
    // fire when any Ajax requests complete
})

ajaxComplete()

Upvotes: 67

Stephen Watkins
Stephen Watkins

Reputation: 25775

You can bind events to dynamically loaded content via jQuery's $.live().

From jQuery http://api.jquery.com/live/:

Attach a handler to the event for all elements which match the current selector, now and in the future.

Upvotes: 1

Related Questions