Raghu
Raghu

Reputation: 323

alt attribute for Image tag in html

Scenario:

 <img src="filepath" alt="image not found">

This will make sure that if the file is not found in the path then the text would be loaded .....

Question: Instead of a alternative text can a image be loaded ?? is there any tags would readily serve my purpose and is there any custom javascript functions which could be given in #alt tag??

Upvotes: 0

Views: 2544

Answers (3)

anand vishwakarma
anand vishwakarma

Reputation: 79

Please refer below code..

Inside onerror function add src path which you want load. If src is image is loaded.

<img onerror="this.onerror=null;this.src='http://www.personal.psu.edu/oeo5025/jpg.jpg'" id="ddd" 
src='http://www.loveimagesdownload.com/wp-content/uploads/2016/08/declaration-of-love_23-2147517078.jpg'/>

Upvotes: 0

JoDev
JoDev

Reputation: 6873

There is a special event wich allow you to make this. It's :

<img src="" onerror="this.src='path/to/default'" />

Upvotes: 0

kamituel
kamituel

Reputation: 35960

You can check if the image loaded in JavaScript:

var img = document.getElementById('image');
if ( img.complete && img.naturalWidth == 0 ) {
  // some error, load alternate image:
  img.src = "path to alternative img";
}

Edit: Complete solution (using onerror from @JoDev's answer) would be:

<script>
function validate (img) {
  // Clear the callback to avoid infinite loop in case
  // new image path would be also invalid.
  img.onerror = null;

  if ( img.complete && img.naturalWidth == 0 ) {
    // some error, load alternate image:
    img.src = "http://example.com/valid_path.png";
  }
}
</script>

<img onerror="javascript:validate(this);" 
     src="http://example.com/some_invalid_path.png"/>

Upvotes: 2

Related Questions