Default image if no image html

Display Default Image when No Image Found

Here’s a solution to display a Default Image in the Image control, when the original image is not available. The same solution can be applied to both ASP.NET Image Controls as well as HTML image controls

asp:Image ID="imgProd" runat="server"
onerror="this.onload = null; this.src='ImageurlORAnyImageHere.jpg';"/>
img id="imgProd1" src="someimage.gif"
onerror="this.onerror=null; this.src='ImageurlORAnyImageHere.jpg';" />

We are using the onerror event of the image tag, which triggers if there is an error while loading an image. If an error occurs, we display ‘ImageurlORAnyImageHere.jpg’ as the default image. You can even add an image url.

If you are looking out to apply the same technique while loading images in an ASP.NET GridView, check my article Loading Images Asynchronously Inside an ASP.NET GridView

About The Author

Suprotim Agarwal

Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books — 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Источник

Default image if no image html

Last updated: Jan 12, 2023
Reading time · 2 min

banner

# Show a default image if image is not found using JavaScript

To show a default image if the original image is not found:

  1. Add an error event listener to the image.
  2. If the image doesn’t load successfully, change its src attribute.
  3. Optionally, change the image’s alt attribute.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> img id="img" src="does-not-exist.png" alt="banner" /> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const img = document.getElementById('img'); img.addEventListener('error', function handleError() const defaultImage = 'https://bobbyhadz.com/images/blog/javascript-show-div-on-select-option/banner.webp'; img.src = defaultImage; img.alt = 'default'; >);

We added an error event listener to the img element.

If the image fails to load, an error event is fired at the element that initiated the load and the onerror() handler on the image is invoked.

If you set the image’s src attribute to a non-existent image, it would re-trigger the error event, causing an infinite loop.

Inside the error handler function, we update the image’s src attribute to a default image and change the value of the image’s alt attribute.

# Show a default image if multiple images are not found

If you need to show a default image if the original is not found for multiple images:

  1. Select the images using the querySelectorAll() method.
  2. Iterate over the collection using the forEach() method.
  3. Add an error event listener to each image.
Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> img src="does-not-exist.png" alt="banner" /> img src="does-not-exist.png" alt="banner" /> img src="does-not-exist.png" alt="banner" /> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const images = document.querySelectorAll('img'); images.forEach(img => img.addEventListener('error', function handleError() const defaultImage = 'https://bobbyhadz.com/images/blog/javascript-show-div-on-select-option/banner.webp'; img.src = defaultImage; img.alt = 'default'; >); >);

We used the document.querySelectorAll method to select all of the img elements on the page.

The method takes a string containing one or more valid CSS selectors.

The function we passed to the forEach() method gets called with each image in the NodeList .

On each iteration, we add the error event listener to the image to provide a backup if the original doesn’t load.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to set a default image when an image fails to load

Profile picture

Image loading in websites fail for many reasons. It could be that the src of the image contains a broken link. Or, the internet connection may be poor, and not enough to fetch the image from an external source. Or, the image’s server (which may be external) may be down.

When images don’t load, the alt text is displayed in the container with a tiny icon signifying a broken image, like so:

Showing alt text of image

This view can affect UX especially when the text begins to exceed the image container.

We can display default iamges (instead of alt texts) when an image is not fetched correctly for whatever reason. And in this article, we’ll see how.

According to [MDN](How to set a default image when an image fails to load),

The error event is fired on an Element object when a resource failed to load, or can’t be used. For example, if a script has an execution error or an image can’t be found or is invalid.

When an image fails to load due to connection, broken link, or whatever reason, the onerror event is fired. And this is where we set the default image.

The idea here is, we declare a callback function such that when the error event is fired, that function with the event object as the argument will be invoked. In that callback function, we can change the src of the image to a default link that we’re sure is not broken, and also maybe exists on the same server.

Now, let’s look at the code side of things.

In Plain HTML and JS:

 img id="image" src="https://broken-link-goes-here" />
// js file const img = document.getElementById("image") img.addEventListener("error", function(event)  event.target.src = "https://default-image-link-goes-here" event.onerror = null >)
function Component()  return ( div> img src="https://broken-link-goes-here" alt="A house with two children standing in front of it" onError=event =>  event.target.src = "https://default-image-link-goes-here" event.onerror = null >> /> div> ) >

The same idea goes for other frameworks. In the callback, you reassign a different image link (which will be used as the default) to the src attribute.

One extra thing I did was add event.onerror = null . The relevance of that line is, if for any reasons the newly assigned image link is broken or the image not fetched, the onerror event will be triggered again. And if the image doesn’t load again, another trigger. And there you have an infinite loooooooop 🥵.

Assignining null to the event prevents that. If the new image link doesn’t work, the error event does not call a callback function and then the alt text will be displayed.

And that’s how to set a default image when an image fails to load.

Articles written with ❤ by
Dillion Megida

Источник

Default image if no image html

Gray Pipe

Answered by:

Question

User568213651 posted
Hello all, Suppost that an image is located on WWW. I am trying to link products to our images that are hosted on our host website. I would like to display a default image if the link that I am calling is empty instead of getting that general html no image icon. Help please Thanks. I am working with VS2008 in ASP.NET 2.0.

Answers

User-1267218547 posted
Hi, You can check an image exists with ajax http://www.daniweb.com/blogs/entry654.html Or add a HttpHandler to check the image.

public void ProcessRequest(HttpContext context) < context.Response.Expires = 0; context.Response.Clear(); context.Response.ContentType = "image/jpg"; if(File.Exist(context.Request.PhysicalPath)) context.Response.WriteFile(context.Request.PhysicalPath); else context.Response.WriteFile(context.Request.PhysicalApplicationPath + "images/error.jpg"); context.Response.End(); >

User-899603011 posted
Hi, Please follow this link — http://forums.asp.net/t/1360546.aspx Best of Luck .

All replies

User-442214108 posted
Is the data, path etc being housed in a database, or are you hard-coding your images, data, etc?

User-1626282078 posted
What kind of control are you trying to use to display the image? asp:Image, asp:ImageButton, img, etc.? Depending on what your using to display the image, you options for alternate/default image or text will differ.

User568213651 posted
Good point. I am sorry all I was doing was using the html However I would use the asp image if that is a better and more flexible option. The images are not in a database just links and I am basing the link off of what a user enters for the item number using the to edit the link.

User1024576976 posted
just use try catch and check whether file exists,if exists then display it otherwise the exception will be thrown and you will be moved to the catch scope.Here you can display your default image. Thanks

User735634802 posted
Hi Friend, If you want to display image on your page if the image is not available on the desitred url. To do so, First of all create asp image control on the page to show image one page and give that the default url like this code. < asp : Image ID ="imgDisp" ImageUrl ="~/images/default.jpg" runat ="server" AlternateText ="Image Can Not Display"/>Then check the url in server code whether the image is available or not. If the image is not available then do not overwrite that image url. If image is available the overwrite that ImageUrl property like. imgDisp.ImageUrl = «image url at run time» ; Sincerely,
Pradeep Kr. Sharma Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

User-1267218547 posted
Hi, You can check an image exists with ajax http://www.daniweb.com/blogs/entry654.html Or add a HttpHandler to check the image.

public void ProcessRequest(HttpContext context) < context.Response.Expires = 0; context.Response.Clear(); context.Response.ContentType = "image/jpg"; if(File.Exist(context.Request.PhysicalPath)) context.Response.WriteFile(context.Request.PhysicalPath); else context.Response.WriteFile(context.Request.PhysicalApplicationPath + "images/error.jpg"); context.Response.End(); >

User-899603011 posted
Hi, Please follow this link — http://forums.asp.net/t/1360546.aspx Best of Luck .

Dev centers

Learning resources

Community

Support

Programs

logo

© 2023 Microsoft

Источник

Читайте также:  Php цифры с нулем
Оцените статью