Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

see if src of img exists

when I place an img tag I create the src attribute dynamically. Is there a way of testing if the src (path where the image is located) actually exists with javascript in order to avoid getting:

enter image description here

like image 247
Tono Nam Avatar asked Jan 26 '12 17:01

Tono Nam


People also ask

How check image exist or not in jquery?

Use the error handler like this: $('#image_id'). error(function() { alert('Image does not exist !! '); });


2 Answers

You can use the error event:

var im = document.getElementById('imageID'); // or select based on classes im.onerror = function(){   // image not found or change src like this as default image:     im.src = 'new path'; }; 

Inline Version:

<img src="whatever" onError="this.src = 'new default path'" /> 

Or

<img src="whatever" onError="doSomething();" /> 

<img> tag supports these events:

  • abort (onAbort)
  • error (onError)
  • load (onLoad)

More Information:

  • JavaScript Events
  • jQuery's error
like image 156
Sarfraz Avatar answered Sep 19 '22 00:09

Sarfraz


you can make a previous ajax call (with head method) and see the server return code or you can use onerror event to change url or make it hidden, e.g.

<img src="notexist.jpg" onerror="this.style.visibility = 'hidden'"> 

(I've used inline attribute just to explain the idea)

like image 42
Fabrizio Calderan Avatar answered Sep 20 '22 00:09

Fabrizio Calderan