0

Each time a new message is sent, it is automatically displayed for each user. The message consists of the message, a timestamp, and the sender's profile picture. Using the HTML template, the message and timestamp displays but not the image.

HTML


<!--template for javascript incoming-->
                  <template id="incoming_template">
                    <div class="incoming_msg_img" data-template="temp_img">

                    </div> 
                      <div class="received_msg">
                        <div class="received_withd_msg" aria-describedby="name">
                          <small id="name" data-template="sender">User</small>
                          <p data-template="temp_message"></p>
                          <span class="time_date" data-template="temp_time"></span></div>
                      </div>
                  </template>

JavaScript

$(function () {

                // Get template
                var template = $("#incoming_template").html();

                var template_dom = $('<div/>').append(template);            
                
                // Create a new row from the template
                var $row = $(template);
                

                var img = "<img src=../static/avatars/beard.png>";


                // Add data to the row
                $row.find("p[data-template='temp_message']").text(data.msg);
                $row.find("span[data-template='temp_time']").text(data.timestamp);
                $row.find("small[data-template='sender']").text(data.sender);
                $row.find("div[data-template='temp_img']").html(img);
            
                // Add the row to the table
                $("#newmsg").append($row);

                updateScroll();
            });
Andy Chen
  • 85
  • 1
  • 7

1 Answers1

0

Currently, you are wrapping some HTML string in a jQuery object. You need to temporarily create a DOM object out of your template HTML so that the jquery find function can properly find the elements inside a DOM tree. See revisions below:

// Get template
var template = $("#incoming_template").html();

// Add this line to your code
var template_dom = $('<div/>').append(template);

// Create a new row from the template
var $row = $(template_dom);

Then change this line:

$row.find("div[data-template='temp_img']").text(img);

To this:

$row.find("div[data-template='temp_img']").html(img);

Since you are appending a markup and not some text.

Read more here: What is the difference between jQuery: text() and html() ?

95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51