Reputation: 52
I have a page that dynamically loads content with a .get request from clicking a button. The HTML page that loads I can not get any jquery selector to target anything on that page. I tried putting the script for the alert on the page that gets loaded as well with no luck.
What I think is happening is when the page is loaded the content I am trying to target was not there and it doesn't check again when the page is loaded? This is just my guess, any help would be greatly appreciated.
This is where the page content is loaded to the main page dynamically.
$(".load-page").click( function(){
var href = $(this).attr("data-href");
$.get(href,function (hdisplayed) {
$("#content").html( hdisplayed );
});
});
This is what I am using to to select content on the page.
$(function() {
$("#div").click(function(){
alert("hello");
});
Upvotes: 0
Views: 6807
Reputation: 1251
Event handlers will work with the '.on' biding on the parent element. But if you only need to select the dynamically loaded elements for some other manipulation, you need to wait for the content to actually load.
$('#parent_element').load(
url, //url for the AJAX request
{}, //data to be sent with the request
function(){ //this function will be called when content has loaded
$('#dynamic_child_element').css('background','#000');
}
);
Upvotes: 1
Reputation: 14123
Try to use a live handler:
$(document).on('click', '#div', function() {
alert("hello");
});
It is binded to document and works with dynamically added content while .click()
is binded to exact elements that already existed when .click()
has been called.
See also the detailed documentation for the on()
method of jQuery.
Upvotes: 3
Reputation: 312
You want to use .on() which will attach to dynamically added elements.
$(function() {
$("body").on('click', '#div', function() {
alert("hello");
});
});
Also, don't give elements id's with div or span or other element names its just bad practice. I would recommend using targeted class selectors rather than id's anyway, specially for dynamically generated content. Also I set body as your target since I am not sure what the structure of your code is(where your #div element is)
Upvotes: 2