April 7, 2012

Does the <img> tag have an "onsuccess" attribute?

Question by Shahrukh

Does the <img> tag have an "onsuccess" attribute? Like "onerror".

I am loading an image. I bind an event with JQuery, which changes image onerror.
i want to show an alert "ONERROR Image loaded successfuly" if onerror image successfully loaded. Otherwise it will show alert "ONERROR image not found".

EDIT:
onload shows alert after loading image. but didn’t tells us that "your real image is loaded" or "browser's default error image is loaded". check here…

http://jsfiddle.net/extremerose71/cHuu6/6/

Answer by Engineer

If you wrote something like:

<img id="im3" src="http://ssl.gstatic.com/gb/images/j_f11bbae8.png" />​

And also wrote:

$(window).load(function() {
   $("#im3").load( function (){
      alert('load');
   }).error( function (){
      alert('error');
   });
});

(as in jsfiddle onLoad is corresponded to $(window).load) , you will never get any alert, because $(window).load will be called after all resources is already loaded.

But if you would remove src from img:

<img id="im3"/>​ 

And then add this

$("#im3").attr('src','http://ssl.gstatic.com/gb/images/j_f11bbae8.png' )​​​​​​​​​​​​​​;

line after the load and error listeners , you will see an alert.

So the main problem was , that you were adding listeners after the image has already loaded or failed to load.

Answer by Starx

You can do this using onerror and onload event handlers

var im = document.getElementById('imageid');
im.onload = function() {
   //handler
};

im.onerror = function() {
   //handler
};

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!