The server emits the comment back to all clients and the client appends
to a <ul> item (through simple DOM manipulations).
</form>
</p>
+ <ul id="comments">
+ </ul>
+
<p>
<form action="" id="comment-form">
<input id="comment" type="text" style="width:100%" autocomplete="off" placeholder="Add a comment" />
<script>
var socket = io();
+ var comments = document.querySelector("#comments");
var form = document.querySelector("#comment-form");
var comment = document.querySelector("#comment");
comment.value = '';
}
});
+
+ socket.on('comment', function(msg) {
+ var item = document.createElement('li');
+ item.textContent = msg;
+ comments.appendChild(item);
+ });
</script>
</body>
</html>
});
io.on('connection', (socket) => {
- console.log('a user connected');
- socket.on('comment', (comment) => {
- console.log('comment: ' + comment);
+ socket.on('comment', (msg) => {
+ io.emit('comment', msg);
});
});