Replacing an image within a comment section using a third-party application tutorial

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&amp;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;
}

Answer №1

Utilizing jQuery enables you to easily target the container holding your comments and search for the initial element that distinguishes each comment uniquely. Subsequently, you can iterate through the obtained array and modify the image. The main consideration then becomes whether to apply a consistent image or one that is distinct.

Here's an illustrative example I crafted for you. The comments container represents the designated element on your website where all comments are displayed. Within it, the first div specifies what sets each comment apart. In this scenario, I substituted various images with similar ones featuring cats.

$(document).ready(function() {

  var comments = $("#comments-container").find("div");

  //console.log(comments);

  $(comments).each(function(i, item) {

    // console.log(item);

    $(item).find('img').attr('src', 'https://loremflickr.com/220/200/cat');

  });


});
#comments-container>div {
  margin: 20px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='comments-container'>


  <div id="comment_1">
    <img src="https://loremflickr.com/320/240/dog" />
  </div>
  <div id="comment_2">
    <img src="https://loremflickr.com/320/240/girl" />
  </div>
  <div id="comment_3">
    <img src="https://loremflickr.com/320/240/boat" />
  </div>
  <div id="comment_4">
    <img src="https://loremflickr.com/320/240/statue" />
  </div>
  <div id="comment_5">
    <img src="https://loremflickr.com/320/240/guitar" />
  </div>



</div>

").find('img') .attr('src','steam-conasuaga-east-cowpen-trail-4_480px.jpg');

The rationale behind using an array in your code may not be entirely clear. Typically, an id is meant to be unique within a document. Utilizing getElementById() does not usually result in an array.

Answer №2

The function document.getElementsById is throwing an error as it is not a valid function. It seems like you intended to use getElementByid instead, which only returns a single node rather than an array. You can try the following code snippet:

document.getElementById("comment_14368294").firstChild.src = "team-conasuaga-east-cowpen-trail-4_480px.jpg";

Answer №3

If you need to adjust the image path only in case of a loading failure, one suggestion is to attach the onerror event to all images.

The following code will monitor any image error events and switch the path to your default image if it fails to load.

$(function(){   
    $(window).load("load",function(e){  
        var defImg = "default image url"; // Default image path
        $(".comment").find("img").bind("error",function(){
            $(this).attr("src",defImg);
        }); 
    })

})

I opted for using $window.load() to bind my event based on your question about integrating a third-party comment module. Sometimes, the third party may not finish rendering before the ready event triggers.

Hopefully this solution proves useful, and pardon any grammar errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize JavaScript to assign a button with identical functionality as another button

After developing a slick slider, I decided to add custom arrows. The standard method from slick involves using prevArrow: and nextArrow:, but I wanted the buttons outside of the slick-slider container. To achieve this, I placed additional prev and next but ...

Build an HTML table with immovable side columns on both the left and right sides

Currently facing a dilemma here. I developed a booking system for a client and didn't prioritize making it responsive. However, the need for responsiveness arose last week. I thought my code was prepared for this, but turns out it's not as respon ...

Is there a CSS property that is determined by the position of an element

My objective is to display a styled tooltip in an HTML document. To achieve this, I have written the following code: .word-with-tooltip{ position:relative; } .tooltip{ position:absolute; bottom:1.5em; right:0; height:100px; width:200p ...

Utilizing MongoDB arrays for efficient value retrieval within array attributes

I'm currently working with the code below: // Defining my search array var charArray=['a','b','c'] { name: 'object1', myChar: ['a','v','x'] } { name: 'object2&ap ...

Show both text and image inputs side by side within a table

Hey there, I'm trying to create a table with both text and image inputs inside. Here's the code I've attempted: <tbody> <tr> <td class="inputs"> <input type=" ...

What is the best way to send the article id to the pagination page using Ajax?

I am currently working on implementing a pagination system for a category result page that displays articles using AJAX. I am utilizing a WHERE clause and need to send the article ID to the AJAX page. Here are my code snippets: include_once '../db.ph ...

What is the best way to update specific values in a react multiselect component?

Within my modal, I have a form where I can edit my model. One of the fields in this form is a multi-select tag field called "tags", which is an array of objects consisting of labels and values as illustrated below. To populate this tag field, I have a dum ...

Vue dropdown component mistakenly triggers event on incorrect element

Utilizing the incredible Vue Multiselect component for my project. Incorporated 8 dropdown multi-select elements into my form structure. A peculiar issue arises when an option is chosen from the second dropdown - it triggers the onSearchResellerCompanies ...

Error encountered in React and Redux: Unable to read properties of undefined (specifically 'region')

Whenever a user clicks on edit, I am fetching data (an object) into a redux state and displaying it in a textarea. Here is the code snippet: const regionData = useSelector((state) => state.myReducer.userDetailList.region); The problem arises when this ...

What is the best way to incorporate text within an ongoing animation?

While browsing through Codepen, I came across an intriguing HTML/CSS animation featuring a rotating diamond. I've been attempting to enhance this animation by adding a text, such as "HELLO," in the center of the diamond. Ideally, I would like toggling ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Having trouble with the mat-select dropdown not updating with patchvalue?

Can you help me understand why my dropdown is not working as expected? I have tried using value binding and ngModel, but it's still not functioning properly. <mat-form-field> <mat-select placeholder="Team NO" formControl ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

A guide to showcasing a series of strings in a react element

My aim is to present an array of strings on distinct lines within my React component by utilizing the following code: <div> {this.props.notifications.join('\n')} </div> Nonetheless, it appears that this a ...

A tutorial on preventing backbone.js from automatically adding /# when a dialog is closed

Whenever I navigate back on my backbone page, it automatically adds /# to the URL. This results in loading an empty index page from the Rails home view when pressing back again. Disabling turbolinks fixed this issue for me. However, another problem arises ...

Assistance needed in optimizing my JQuery Fading Gallery for better efficiency

Check out the fantastic image fading JQuery gallery on the homepage of this website - . Take a look at the JQuery script: $('.fadein img').addClass('js'); $(function() { $('.fadein').children().eq(0).appendTo('.fad ...

Incorporating a drag functionality to choose a range of dates from a calendar with the help of CLNDR.js

I am developing a custom calendar using the CLNDR.js library, which is currently functioning well for selecting individual dates. However, we now have a requirement to allow users to select a range of dates by dragging across multiple calendar boxes. http ...

The state is not being processed properly

One challenge I am facing involves two components where a user can attach an image or gif to a post. When the image is clicked, a modal pops up and I aim to pass the data back to the modal so that the clicked image displays. To address this issue, I imple ...

Is it necessary to remove event bindings and disable plugins before navigating away from a page in Jquery Mobile or Jquery?

I've incorporated multiple plugins into a Jquery Mobile website and am searching for the most effective method to "tidy up" when transitioning away from a page that remains in the DOM. The question at hand is whether I should attempt to unbind/off/un ...

When a Vue.js Directive is inserted or bound, it actually takes precedence over the click event

Imagine having multiple dropdowns or elements on the page that all utilize a directive called "closable". This directive triggers an expression if the element clicked is outside of the element using the directive. The intended behavior is that when clicki ...