0

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.

Control Freak
  • 12,965
  • 30
  • 94
  • 145

3 Answers3

3

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
   } 
 });
PeterKA
  • 24,158
  • 5
  • 26
  • 48
user229044
  • 232,980
  • 40
  • 330
  • 338
2
  1. events are lowercase
  2. this inside the onload function is not the image in the DOM
  3. you should always set the source after the onload handler is bound
  4. you seem to be missing a closing parenthesis in the alert()

.

$("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();

});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • #3 is wrong; you do not need to set the `onload` before the `src`. – user229044 Jul 03 '14 at 18:19
  • It's a bit old, but here's a [SO question](http://stackoverflow.com/questions/1038327/image-onload-not-firing-twice-in-ie7) about this. There have been issues with setting the source before the onload handler, so it's common to make sure you set the source after the onload handler, as that at least makes sure there are no issues with it, and it's such an easy fix. – adeneo Jul 03 '14 at 18:47
  • That question is from 2009, and is about a dead browser. There's very little value in perpetuating hacky fixes for dead browsers. – user229044 Jul 03 '14 at 18:56
0

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.

PeterKA
  • 24,158
  • 5
  • 26
  • 48