I happen to have a stylized image with a list inside it in some HTML page.
If the image cannot be shown, I want to have a normal HTML list instead of it (in a similar vein to an alt text, but with HTML tags and not just text).
Is there a best way to do that? (like a CSS rule or something?)
Thanks
CodePudding user response:
There is a standard way to do this without resorting to JavaScript. Use the object element instead of the img element. If the image can't be displayed, the content of the object element is used. So:
<p>When the image displays:</p>
<object data="https://via.placeholder.com/50" style="height:50px">
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
</object>
<p>When the image doesn't display:</p>
<object data="https://error.placeholder.com/50" style="height:50px">
<ul>
<li>list item 1</li>
<li>list item 2</li>
</ul>
</object>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can listen for the error
event, which fires when the resource can't be loaded:
function badImage(imageElement){
imageElement.outerHTML = "This image can't be shown"
}
<img src="https://.com" onerror="badImage(this)">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
the list is overlaped by the image normaly. if the image has an error loading, it will become invisible.
not 100% sure if it will work though.
css:
img {
z-index: 1;
position: absolute;
top:0px;
left:0px;
}
ul {
/*z-index: 0;*/
position: absolute;
top:0px;
left:0px;
}
html:
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
<img src="image.jpg" onerror="document.querySelector('img').style.visibility = "hidden"">
you can style the list however you like.