-1

I am working on a project in which I will be getting HTML file from another source and it can have multiple images, so I cannot modify HTML file. I am planning to write a java script in order to solve below issue.

But that file has some img sources which are not present so image is not getting loaded.

I want to display a particular message like "Please login in order to view this image" instead of unloaded image if it is not loaded while if other images are loaded they should be shown as it is.

It will be helpful if someone can provide any feedback.

  • Could you maybe add some code? Like many times before, this is not a coding service. – Yannick Dec 03 '21 at 13:33
  • Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+show+text+image+error+site%3Astackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Dec 03 '21 at 13:36

2 Answers2

1

Here is how to test after the page has loaded

window.addEventListener("load", event => {
  document.querySelectorAll('img').forEach(img => {
    const isLoaded = img.complete && img.naturalHeight !== 0;
    if (!isLoaded) img.outerHTML = "Please login in order to view this image"
  })
})
<img src="image1.jpg" /><br/>
<img src="image2.jpg" /><br/>
<img src="image3.jpg" /><br/>
<img src="image4.jpg" /><br/>
<img src="image5.jpg" /><br/>
<img src="image6.jpg" /><br/>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

If I correctly understand what your're asking, you can do this by using alt within the HTML tag. For example:

<img src="computer.jpg" alt="Computer Image" width="500" height="600">

If you run that snippet, you can see that since the image is not defined, text will appear.

Scollier
  • 575
  • 6
  • 19
  • I cannot edit HTML file need javascript or jquery function to display a particular text if an image is not loaded. – Simran Gehani Dec 03 '21 at 13:59
  • Take a look at all the answers provided in the link above: https://stackoverflow.com/questions/9815762/detect-when-an-image-fails-to-load-in-javascript – Scollier Dec 03 '21 at 14:05
  • I did look into it but most of them describe a function in which URL is passed as parameter. But in my case I cannot call this function as HTML file cannot be edited. – Simran Gehani Dec 03 '21 at 14:10