Display only Alt text in image tag html

2.9k views Asked by At

I want to display only alt text if the image is not there in the path. It is displaying properly in Firefox, but in chrome it displays broken image link then alt text. I tried doing like this

I tried jquery

<script type="text/javascript"> 
  function hideImage(img)
{
   img.style.display = "none";
}
</script>

But it doesn't even display alt text. How to display alt text through this.

2

There are 2 answers

2
Rory McCrossan On

You can hook to the error event that gets raised when an img element fails to load. You can then call replaceWith() to show the alt text in its place. Try this:

$('img').on('error', function() {
  $(this).replaceWith(function() {
    return $(this).prop('alt');
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's an image that won't load: <img src="doesnt_exist.jpg" alt="foo bar" />

5
Rajshekar Reddy On

CSS Solution - May not be compatible in older browsers


Using the attr() expression. You can replace the default alt text that shows, by positioning the pseudo-element on top of the default text, hiding it from view.

img:after {  
  content: attr(alt);
  font-size: 16px;      
  color: rgb(100, 100, 100);
  display: block;
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #fff;
}
<img src="doesnt_exist.jpg" alt="No Image" />

Credits to Styling Broken Images there are more cool tricks there.