Control Freak
Control Freak

Reputation: 13233

Trouble using onLoad with .each()

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

Answers (3)

user229044
user229044

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

adeneo
adeneo

Reputation: 318222

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

});

Upvotes: 2

PeterKA
PeterKA

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

Related Questions