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() {});
2
  • 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? Commented Nov 19, 2010 at 15:16
  • The latter. There is no $(document).ready in the loaded .html file. Should there be? Commented Nov 19, 2010 at 16:07

4 Answers 4

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

ajaxComplete()

Sign up to request clarification or add additional context in comments.

1 Comment

But that will fire after every AJAX call... which could affect performance, right? Is there a way to manually trigger the jquery?
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

2 Comments

I thought it was $.live() for dynamically created objects. api.jquery.com/live
I think you mean the live function, which is the equivalent of bind, but works for dynamically created elements.
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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.