Reputation: 23
I wanted to load all images from a directory using ajax call and accept one after it is added to html. I have successfully load all images. But My problem is that i can't access its attribute in jQuery after it is inserted in html.
How can I access an image attribute after it is been added by jQuery ajax call.
My jQuery code for accessing image src is
$("button").click(function(){
$("#div1").load("demo.php");
});
$("#div1 img").click(function(){
console.log($(this).attr("src"));
});
my html is :
<div id="div1"></div>
<button>Click Here</button>
and my demo.php is
<?php
$directory = /path/to/folder/;
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
echo "<img class='imgr' src='$image'/>";
}
?>
I am able to load images to the div1 element but I can't access its attributes. I have changed the '#div1 img' to 'img' and '.imgr' but with no luck.
Upvotes: 1
Views: 202
Reputation: 81
You need to have click event on parent div in order to delegate click events to children that are not part of the DOM yet, please check this link on event delegation
Try this instead:
$("#div1").on('click', 'img', function(){
console.log($(this).attr("src"));
});
Upvotes: 1
Reputation: 9992
I would suggest to use $(document).on("click" , "" , function() {});
$(document).on("click", "#div1 img", function() {
console.log($(this).attr("src"));
});
Upvotes: 1
Reputation: 279
You can't bind click event on elements that doesn't exist when the script is loaded. You can change this:
$("#div1 img").click(function(){
console.log($(this).attr("src"));
});
to this:
$('#div1').on('click', "img", function(){
console.log($(this).attr("src"));
});
Upvotes: 1
Reputation: 928
It's because the data is loaded dynamically.
Change;
$("#div1 img").click(function(){
console.log($(this).attr("src"));
});
to
$( "#div1" ).on( "click", "img", function() {
console.log($(this).attr("src"));
});
Upvotes: 1