Cuz Cuz - 6 months ago 22
Javascript Question

Socket.io chat reload page when message is sent

I'm having a go with the socket.io tutorial at http://socket.io/get-started/chat/, but my problem is that when i send a message the page reloads instead of persisting.

The only difference is that i used pure DOM instead of using jquery as in tutorial. This is the original code:

<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();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>


And this is mine:

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var socket = io();
document.querySelector('form')
.addEventListener('submit', function () {
socket.emit('chat message',
document.querySelector('#m').value);
document.querySelector('#m').value = '';
return false;
});

socket.on('chat message', function (msg) {
var li = document.createElement('li');
document.querySelector('#messages').appendChild(li);
li.innerText = msg;
});
</script>


If i replace mine with the jquery one, it works as a charm.
Can anyone see where the problem is?

Answer

Use preventDefault, return false doesn't work for addEventListener

document.querySelector('form').addEventListener('submit', function (e) {
    socket.emit('chat message', document.querySelector('#m').value);
    document.querySelector('#m').value = '';
    e.preventDefault();
});