23

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() {});
Bryce
  • 8,313
  • 6
  • 55
  • 73
mmcglynn
  • 7,668
  • 16
  • 52
  • 76
  • Just to confirm, your $(document).ready functions are not executing within the .html you are loading into your master page? or the $(document).ready is not locating the elements you are loading via AJAX? – WiseGuyEh Nov 19 '10 at 15:16
  • The latter. There is no $(document).ready in the loaded .html file. Should there be? – mmcglynn Nov 19 '10 at 16:07

4 Answers4

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

ajaxComplete()

Jman
  • 928
  • 7
  • 12
  • 1
    But that will fire after every AJAX call... which could affect performance, right? Is there a way to manually trigger the jquery? – Bryce Nov 03 '13 at 02:00
3

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

Adam Kiss
  • 11,811
  • 9
  • 48
  • 81
1

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.

Stephen Watkins
  • 25,047
  • 15
  • 66
  • 100
0

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

Scott Evernden
  • 39,136
  • 15
  • 78
  • 84