Mercurial > cosocket
view openwebchat.js @ 47:42b8c0229cd0
Fixed a scrolling problem.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Tue, 28 Apr 2009 17:41:34 +0000 |
parents | 27785e0ac4d8 |
children | 9c66f1f840f7 |
line wrap: on
line source
var OpenWebChat = { startMessageListener: function startMessageListener(options) { var req = new XMLHttpRequest(); req.multipart = true; req.open('GET', 'listen/multipart', true); req.overrideMimeType('application/json'); req.addEventListener( "error", function() { options.onError(null); }, false ); req.addEventListener( "load", function onload(evt) { var msg; var errorOccurred = false; try { msg = JSON.parse(req.responseText); } catch (e) { options.onError(e); errorOccurred = true; } if (!errorOccurred) options.onMessage(msg); }, false ); req.send(null); }, sendMessage: function sendMessage(msg) { var req = new XMLHttpRequest(); req.open('POST', 'send', true); req.overrideMimeType('application/json'); req.send(JSON.stringify(msg)); } }; $(window).ready( function() { var ENTER_KEYCODE = 13; $('#outgoing-message').focus(); $('#outgoing-message').keydown( function(evt) { var content = $(this).val(); var author = $('#name').val(); if (evt.keyCode == ENTER_KEYCODE) { if (content) { $(this).val(''); var msg = {content: content, time: new Date()}; if (author) msg.author = author; OpenWebChat.sendMessage(msg); } evt.preventDefault(); } }); OpenWebChat.startMessageListener( {onMessage: function onMessage(msg) { var block = $('#templates .message').clone(); // Try to dynamically determine if the message is HTML or not. var parser = new DOMParser(); var dom = parser.parseFromString('<xml>' + msg.content + '</xml>', 'text/xml'); if (dom.firstChild.nodeName == 'parsererror') $('.content', block).text(msg.content); else $('.content', block).html(msg.content); var author = msg.author ? msg.author : 'Anonymous'; if (author != $('#content .author:last').text()) $('.author', block).text(author); else $('.author', block).remove(); $('.timestamp', block).text(msg.time); block.hide(); $('#incoming-messages').append(block); block.slideDown( function() { window.scrollTo(0, $('#bottom').position().top); }); }, onError: function onError(exception) { if (window.console) window.console.log('The error', exception, 'occurred.'); var error = $('#templates .error').clone(); error.hide(); $('#incoming-messages').append(error); error.slideDown(); } }); });