Reputation: 2555
I have a problem with the following code:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="container"></div>
<script>
var html = "";
var imagesArr = [
"https://2.bp.blogspot.com/-RHUhIkxWXfM/V0knRDiexII/AAAAAAAAAok/gBHYhd4KheAlaPX_LF6rDHkPZ9B4YS6VACLcB/s1600/napolo%2B25%2Bjp.jpg",
"https://4.bp.blogspot.com/-0rDtgu8yH2A/V0knhAVCgyI/AAAAAAAAAoo/zwno2cyB50UKWAlPM41zL--o7OrAKCWHQCLcB/s1600/nike%2B25jp.jpg",
"https://4.bp.blogspot.com/-_w5bgf-rTag/V0knJckJ6II/AAAAAAAAAog/NgHKMdhlCCw9his5PGPhPcFRRdwDzTgXACLcB/s1600/jordan25jp.jpg" ];
for ( var i = 0; i < imagesArr.length; i++ ) {
html += "<div><img src=\"" + imagesArr[ i ] + "\" id=\"img_" + i + "\"></div>";
$( "#img_" + i ).off();
$( "#img_" + i ).on( "load", function() {
console.log( "#img_" + i + " is loaded! Its size is: " + $( "#img_" + i ).width() + "x" + $( "#img_" + i ).height() );
} );
}
$( "#container" ).html( html );
</script>
</body>
</html>
I use the latest version of JQuery and the latest version of Google Chrome (MacOS Sierra). I try to make JQuery's load event work but in my console I get nothing. What's the problem with the code?
Upvotes: 0
Views: 790
Reputation: 2678
Try this ;)
You are binding event to image before adding them to DOM
;
for (var i = 0; i < imagesArr.length; i++) {
html += "<div><img class="sizeAfterLoad" src=\"" + imagesArr[ i ] + "\" id=\"img_" + i + "\"></div>";
}
$("#container").html(html);
$(function(){
$(".sizeAfterLoad").off('load').on('load', function() {
console.log("#" + $(this).attr('id') + " is loaded! Its size is: " + $(this).width() + "x" + $(this).height());
});
});
Upvotes: 2