I am facing a challenge with replacing an image in the comment section of my website. The comment section is hosted on a third-party server, and unfortunately, I do not have access to it.
Previously, images added by the comment provider HTML Comment Box were displaying correctly for about 6 months before suddenly showing up as "404" errors on their end.
Desperate to remedy this situation, I attempted to replace the broken image with one from my own server using the following code snippet:
<script>
$(document).ready(function() {
document.getElementById("comment_14368294")[0].src = "team-conasuaga-east-cowpen-trail-4_480px.jpg";
});
</script>
Unfortunately, my attempts were unsuccessful. Upon inspecting the third party's code via Chrome Inspector, I discovered the HTML structure of the comment that needed modification:
<div class="comment" id="comment_14368294">
<span class="date">(Apr 7, 2019) </span>
<span class="author hcb-mod"><b class="author-name">Conrad Easley (mod)
</b>said:</span>
<blockquote>
<img align="left" class="gravatar"
src="https://www.gravatar.com/avatar/2484aca7544b9b228bbd67c0be236137?
s=40&d=http%3A%2F%2Fhtmlcommentbox.com%2Fstatic%2Fimages%2Fgravatar.png">
Team Conasauga Workday on East Cowpen Trail April 6th, 2019
</blockquote>
<a href="https://www.htmlcommentbox.com/storage/lg_14368294_team-conasuaga-east-cowpen-trail-4_480px.jpg">
<img src="https://www.htmlcommentbox.com/storage/14368294_team-conasuaga-east-cowpen-trail-4_480px.jpg">
</a>
<p class="hcb-comment-tb">
<a class="hcb-flag" href="javascript:hcb.flag('14368294')">
<img src="https://www.htmlcommentbox.com/static/images/flag.png">flag
</a>
<a class="hcb-like" href="javascript:hcb.like('14368294')">
<img src="https://www.htmlcommentbox.com/static/images/like.png">like</a>
</p>
<div class="likes" style="display:none">
<span>0 </span>
<img src="https://www.htmlcommentbox.com/static/images/like.png">
</div>
</div>
To address the issue, I eventually resorted to using CSS pseudo elements - specifically ::before and ::after. These can be utilized to display content only if the original image fails to load. Here's how I achieved this:
#comment_14368294 img {
position: relative;
width: 480px;
height: 360px;
display: inline-block;
vertical-align: text-top;
}
#comment_14368294 img::before {
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
line-height: 200px;
background-color: #fd0;
background: url(https://cohuttawildernesshiking.com/team-conasuaga-east-cowpen-trail-4_480px.jpg) no-repeat;
color: currentColor;
text-align: center;
border-radius: 2px;
display: block;
width: 480px;
height: 360px;
overflow: hidden;
}