Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I hide broken images in javascript?

I have my image inside an if statement:

if (item.image)
   historyHtml += '<a href=' + item.image + ' class="image" target="_blank"><img src="' + item.image +'" width="111px"/></a>';
like image 383
jprim Avatar asked Sep 09 '10 08:09

jprim


People also ask

How do I hide pictures not found icon?

Example to hide the 'Image Not Found' icon i.e. Using jQuery: Using the JQuery error handler function error(), we can catch the error and hide the object using hide() function. Note: The error() function has been removed from jquery version 3.0. and later.

How do you style a broken image in HTML?

You can't style the way that the broken images look but you can use pseudo-elements to create new elements that override the broken image styling with your own. This is done by using :after to create a new element that sits on top of the broken image so we can style it however we want.

Why is my image broken HTML?

An image could be broken for any number of reasons. For example, the image might not exist, it might not be named properly, or the file path in the code might be incorrect. In this article we'll go over more advanced file system concepts, including absolute and relative file paths.


2 Answers

You can use the onerror handler. In the inline form, it looks like this:

<img src="someimage.jpg" onerror="this.style.display='none';" />
like image 152
Piskvor left the building Avatar answered Oct 13 '22 19:10

Piskvor left the building


As @piskvor says, actually loading the image in an img tag is the only way of finding out whether the URL is broken or not. The error event gets fired if loading fails.

But looking at your code, maybe the opposite approach makes most sense: Hide the <a> by default, and show it in the onload event of the image.

Abridged:

<a href=".." id="image228" style="display: none">
 <img src="..." onload="this.parentNode.style.display = 'block'">
</a>
like image 36
Pekka Avatar answered Oct 13 '22 19:10

Pekka