Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if <img src=""> but no image

Tags:

php

image

When trying to display image that's adress doesn't exist you will see default browsers "no image" badge.

How to change it to default "no-image.png" placeholder?

echo "<img src='http://www.google.com/trolol.png'>"; //for example
like image 416
Szymon Toda Avatar asked Dec 06 '25 08:12

Szymon Toda


2 Answers

You can use the onerror attribute, example:

<img src="" onerror="this.src = 'no-image.png';" alt="" />

Demo: http://jsfiddle.net/kNgYK/

like image 75
MacMac Avatar answered Dec 08 '25 21:12

MacMac


<img src='http://www.google.com/trolol.png' onerror="this.src='http://jsfiddle.net/img/logo.png'">​

sample http://jsfiddle.net/UPdZh/1/

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

Syntax

<element onerror="SomeJavaScriptCode">

http://wap.w3schools.com/jsref/event_onerror.asp

like image 26
Shyju Avatar answered Dec 08 '25 20:12

Shyju