javascriptsocket.io-1.0

Avoiding media embedded in div to get refreshed on addition by innerHTML


I am building a chat web app using socket.io and node.I am adding user's chat in a div using innerHTML.But the problem is that when a new message is added to the chat container(div block),the previous media present in chat-container reloads every time a new chat is added.I want to avoid this.Can anyone help me to find a solution for this?I would love to hear your ideas. Here is the abstract code i am using

HTML
<input type = "text" id = "message" placeholder="Type something..." /><i onclick = "sendMessage()" style="color:green;" title="Send" id="sendbtn"></i>

i am not using input in form element

clientJS:

function sendMessage(){
   var msg = document.getElementById("message").value;
   if (msg) {
      postFile({message: msg,id:id, user: user, color: color,roomid:nativeRoom});
      socket.emit("msg", { message: msg,id:id, user: user, color: color,roomid:nativeRoom});             
   }
}
socket.on("newmsg",function(data){
   postFile(data);
   //Actually postFile is here because it can include video,audio as well
});
function postFile(data){
//here i want to prevent message-container div from reloading its previous media(i have ignored most of the css code to make it precise)
   document.getElementById('message-container').innerHTML += '<div class="messages '+data.user+'chatpiece" id="'+data.id+'"><div><div><b>'+data.user+'</b><img src="'+userprofileimagelink+'"/></div><span>' +{time_when_message_posted} +'</span></div><hr><span style="max-width:100%;word-wrap:break-word;font-size:1.1em;" class="messagemain">' +data.message+"</span></div>"; 
}

server-side:

socket.on('msg',function(data){
  socket.broadcast.to(data.roomid).emit('newmsg',data);
});

I want to avoid reload of video and audio media present in chat container when a new message will be added. How may i achieve this?


Solution

  • Consider appendChild instead of modifying the .innerHTML each time. Once a web page renders html, it becomes DOM. Append to the DOM instead of "converting DOM back into html via innerHTML each time and then appending additional HTML strings to that conversion" (like you're doing). Learn about DOM if you don't know it.