Skip to content

Instantly share code, notes, and snippets.

@clauswitt
Created June 5, 2011 17:23
Show Gist options
  • Select an option

  • Save clauswitt/1009189 to your computer and use it in GitHub Desktop.

Select an option

Save clauswitt/1009189 to your computer and use it in GitHub Desktop.
Client side script for socket.io demo
var socket = new io.Socket();
//When a new mesasge arrives, create a dom node with the text inside, and place it
//in the top of the messages div.
//The color switches between red and blue depending on the sentCounter parameter in the message.
socket.on('message', function(data){
var elm = document.createElement('p');
var messagesDiv = document.getElementById('messages');
elm.innerHTML = data.message;
if(data.sentCounter % 2 == 0) {
elm.style.color = '#f00';
} else {
elm.style.color = '#00f';
}
if(messagesDiv.firstChild) {
messagesDiv.insertBefore(elm, messagesDiv.firstChild);
} else {
messagesDiv.appendChild(elm);
}
});
//Disable connect button, when connected - enable disconnect button instead
socket.on('connect', function(){
document.getElementById('connectButton').disabled = true;
document.getElementById('disconnectButton').disabled = false;
});
//Disable disconnect, when disconnect - enable connect button instead
socket.on('disconnect', function(){
document.getElementById('connectButton').disabled = false;
document.getElementById('disconnectButton').disabled = true;
});
//A function to allow events to work on both IE and real browsers.
function setEvent(elmId, eventName, func) {
var elm = document.getElementById(elmId);
if(elm.addEventListener) {
elm.addEventListener(eventName, func, false);
} else {
elm.attachEvent('on'+eventName, func, false);
}
}
//Setting Event Handlers for buttons, and the textbox.
setEvent('connectButton', 'click', function() {
socket.connect();
});
setEvent('disconnectButton', 'click', function() {
socket.disconnect();
});
setEvent('message', 'keypress', function(evt) {
if(evt.keyCode == 13) {
var message = document.getElementById('message').value;
document.getElementById('message').value = '';
socket.send(message);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment