I need a way to use the jquery .live()
function to act on elements that are loaded via ajax.
For instance a div is loaded via ajax .load()
<
Typically I would handle any actions that occur when the element is loaded either as part of the AJAX callback mechanism or as part of a ready
handler that is included in the returned HTML of the AJAX success callback. The later works well when you want to load a partial view onto the page and want to keep the code with the partial view itself.
Partial View:
<div id="myDiv">
...
</div>
<script type="text/javascript">
$(function() {
$('#myDiv').somePlugin( ... );
});
</script>
Using the callback
$.ajax({
url: '/example.com/code.php',
success: function(html) {
var container = $('#container').html(html);
$('#myDiv',container).somePlugin( ... );
}
});
There isn't a "DOM changed" event and creating one is taxing on the browser. You are best off using the callback for the load method to trigger the functions you need to.
$('#foobar').load('myurl.html',function() {
var mydiv = $("#mydiv");
});
You can't use .live()
with the "load" event. See a non-working example of what you'd like to do here: http://www.jsfiddle.net/S5L6Q/
One approach is to poll with a timer:
var length = $(".mydiv").length;
setInterval(function () {
if ($(".mydiv").length > length) {
length = $(".mydiv").length;
// .. some code
}
}, 100);
This will check every 1/10th of a second to see if some have been added. This might be really expensive depending on the complexity of your selector.
Another option is to hook all of your AJAX calls through a common wrapper that can check the length and executes your code if needed, then executes the supplied callback.
function myAjax(url, data, callback) {
function fullCallback(data) {
if ($(".mydiv").length > 0) {
//... your code...
}
if (callback) {
callback();
}
}
$.get(url, data, fullCallback);
};
The second one is probably the best route, but the first might be easiest.
Have you seen this yet: http://plugins.jquery.com/project/livequery/
For example (expanding on my comment above) this is from the jQuery docs..
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('#mydiv').html(data);
alert('Load was performed.');
}
});
replace the alert with the code you want to run/action you wish to perform
What creates #mydiv? You should be able to simply throw //doSomething right alongside the function that creates #mydiv.
$.post("myURL.html", function(data){
$("#mydiv").html(data);
//doSomething
#mydiv doesn't create itself, after all. However you're creating #mydiv, use that same function to do whatever else you need to do.