Reputation: 13233
Seems like the click function isn't being binded at all, anyone know why?
<img src='img.jpg'/>
$("img").each(function(){
var src = $(this).attr('src');
var img = new Image();
img.src = src;
img.onLoad = function(){
$(this).click(function(){ alert( 'loaded' }); // < not binding
}
});
Don't know what else to try.
Upvotes: 0
Views: 100
Reputation: 239302
JavaScript is case-sensitive.
It's onload
, not onLoad
.
The second problem is that you're binding the click
handler to the newly created var img
, which is never added to the DOM. You're binding it to the img = new Image()
, not the <img>
tag you have at the top.
Ignore this
and try the following:
$("img").each(function(i, el){
var $el = $(el);
var src = $el.attr('src');
var img = new Image();
img.src = src;
img.onload = function(){
$el.click(function(){ alert( 'loaded' }); // < not binding
}
});
Upvotes: 3
Reputation: 318222
this
inside the onload function is not the image in the DOMalert()
.
$("img").each(function(index, element){
var img = new Image();
img.onload = function(){
$(element).on('click', function(){
alert( 'loaded');
});
}
img.src = this.src;
if (img.complete) img.onload();
});
Upvotes: 2
Reputation: 24638
Since you're already using jQuery, you can use it as follows:
var that = $(this);
$(img).load(function(){
that.click(function(){ alert( 'loaded' });
});
Once the image
is loaded, the click
event will be bound to the image.
Upvotes: 0