view openwebchat.js @ 42:f560e6f01c22

misc changes, including now scrolling to the bottom when new messages arrive.
author Atul Varma <varmaa@toolness.com>
date Mon, 27 Apr 2009 23:41:13 -0700
parents c9ba9a45f1dd
children 728f162add5d
line wrap: on
line source

var OpenWebChat = {
  startMessageListener: function startMessageListener(onMessage) {
    var req = new XMLHttpRequest();
    req.multipart = true;
    req.open('GET', 'listen', true);
    req.overrideMimeType('application/json');
    req.addEventListener(
      "load",
      function onload(evt) {
        onMessage(JSON.parse(req.responseText));
      },
      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(
      function(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();

        block.hide();
        $('#incoming-messages').append(block);
        block.slideDown(function() {
                          window.scrollTo(0, $(window).height());
                        });
      });
  });