Reputation: 15291
I have an app that has a 1 page with a DIV that changes its content when the user clicks part of my navigation bar (which is contained within the same page).
So here is my div that I have in my one page app
<div id="content">
</div>
Now I populate this DIV with other html files using the jQuery .load()
method (the HTML files that are fed into the .load method I have stripped of and tags, etc, etc…)
Here’s my JavaScript
$("#content").load("views/"+ pageName + ".html", function(){
// do stuff… like load JavaScript files, etc...
}).fadeIn("fast");
This is working fine however the content which is brought to the page using the .load()
I wish to attach a function to once it has loaded to the DOM.
So say I .load() the following contents from a HTML page using the JavaScript above
<p id="newText"> Blah blah blah blah blah blah blah blah blah blah blah</p>
I wish to raise an event once this is loaded, however I’m unsure what I should bind it to, like .live()
, .on()
or .ready()
… I was thinking of something like this…
$('#newText').load(function() {
alert("Handler for .load() called for newText. This is in the DOM and loaded!");
});
Does anyone know how I should go about this?
* UPDATE *
Okay perhaps I need to explain... I am inherited this app from another developer and I think it was built with a bad architecture / model. Anyway, the pages or views that are loaded have a lot of hidden tabs / toggled content (hence me not liking the architecture) so despite the view / HTML being loaded some of its content may not be available in the DOM when first loaded. That is why I am wishing to detect when a something is loaded into the DOM on top of using the jQuery Ajax .load()
Upvotes: 1
Views: 190
Reputation: 22241
Use either the native .load() callback:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
Or the .ajaxStop() which registers a handler to be called when all Ajax requests have completed.
$('#result').ajaxStop(function() {
alert('Triggered ajaxStop handler.');
});
Upvotes: 1
Reputation: 46647
You can pass a function to load
which it will execute after the load is complete.
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
Upvotes: 0