Jason Singh Jason Singh - 6 months ago 17
HTML Question

DOM duplicating the content when using append

I have a div that works fine if i do this:

$('#chat').innerHTML(data.sticker);


With the above code, what happens is it replaces my previous sticker, but i dont want my previous stickers to go away.

Hence then i do this:

$('#chat').append(data.sticker);


What this above code does is.. its duplicating my data. FOr example, if i click on my "Sticker 1" then Sticker 1 displays and when i click on it again the second time "Sticker 1 " displays 3 times... 1 being the previous one and 2 being the new one, then if i click on it the third time, it displays 6 stcikers...3 being the previous one and 3 being the new one. Can any body help?

My index.html:



function which_sticker(image){
var clickedElement;
var $chat = $('#chat');
var socket = io.connect();
if(image=='1'){
clickedElement = '<img src="stickers/angry/1.png" height="90" width="90"/>';
}
console.log(clickedElement);
socket.emit('send sticker', clickedElement);

socket.on('get sticker', function(data){
console.log(data.sticker);
$('#chat').append('<span class="msg"><b><span id="name_title">' + data.nick + '</span></b><br />' + data.sticker + '<br>');
});
}

<img src="stickers/angry/1.png" onClick="which_sticker('1');" height="90" width="90"/>




Answer

This is happening due to you are assigning event again and again on socket for getsticker whenever user clicks on the element, So everytime you click the event is registered multiple times, so first time it has one registered function second time two, and subsequently.

Here you need to purge event listener or just register it once over the period of your page.... I have given you the example of second below. I have moved event registeration code out of the click event handler

var socket = io.connect();

socket.on('get sticker', function(data){
  console.log(data.sticker);
  $('#chat').append('<span class="msg"><b><span id="name_title">' + data.nick + '</span></b><br />' + data.sticker + '<br>');
});

function which_sticker(image){
  var clickedElement;
  var $chat = $('#chat');

  if(image=='1'){
    clickedElement = '<img src="stickers/angry/1.png" height="90" width="90"/>';
  }
  console.log(clickedElement);
  socket.emit('send sticker', clickedElement);
}