Melbin Mathai Melbin Mathai - 4 months ago 14
Javascript Question

How to append data to a div in client side When server is pushing



var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){

for(i=0; i<10; i++){
io.emit('notification', i);
}
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

<body>

<style type="text/css">

.chatting {
width: 40px;
height: 40px;
border-radius: 50%;
margin-left: auto;
margin-right: auto;
background-color: #a6a6a6;
}
</style>

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
socket.on('notification', function(msg){
alert(msg);

});
</script>

<div class = chatting></div>

</body>





I am just trying to append data to a div in client side when the server is pushing some value. How to do that. Here is my code. The alert is working fine. But I need the Numbers are inserted to the div. Every time server pushing, the number should be changed automatically, like notifications on Facebook.

Thank you.

Answer
   <script>
      var socket = io();
      function appendNotification(notification){
         document.getElementById("notifications").innerHTML = "<div>" +  notification + "</div>";
      }
      socket.on('notification', function(msg){
        appendNotification(msg);
      });
    </script>
    ADD the id to your html
    <div class="chatting" id="notifications"></div>   
Comments