Skip to content

Instantly share code, notes, and snippets.

@stephenlb
Forked from domadev812/messenger.js
Created November 15, 2017 21:06
Show Gist options
  • Save stephenlb/08e9a3b48aeaa0fcee8f5aa8e377fef9 to your computer and use it in GitHub Desktop.
Save stephenlb/08e9a3b48aeaa0fcee8f5aa8e377fef9 to your computer and use it in GitHub Desktop.
pubnub messenger v2
$(document).ready(function () {
// Initialize the PubNub API connection.
pubnub = new PubNub({
publishKey : 'PUBNUB PUBLISH KEY HERE',
subscribeKey : 'PUBNUB SUBSCRIBE KEY HERE'
})
// Grab references for all of our elements.
var messageContent = $('#messageContent'),
sendMessageButton = $('#sendMessageButton'),
messageList = $('#messageList');
// Handles all the messages coming in from pubnub.subscribe.
function handleMessage(message) {
var messageEl = $("<li class='message'>"
+ "<span class='username'>" + message.username + ": </span>"
+ message.text
+ "</li>");
messageList.append(messageEl);
messageList.listview('refresh');
// Scroll to bottom of page
$("html, body").animate({ scrollTop: $(document).height() - $(window).height() }, 'slow');
};
// Compose and send a message when the user clicks our send message button.
sendMessageButton.click(function (event) {
var message = messageContent.val();
if (message != '') {
var publishConfig = {
channel : "chat",
message : {
username: 'test',
text: message
}
}
pubnub.publish(publishConfig, function(status, response) {
console.log(status, response);
})
messageContent.val("");
}
});
// Also send a message when the user hits the enter button in the text area.
messageContent.bind('keydown', function (event) {
if((event.keyCode || event.charCode) !== 13) return true;
sendMessageButton.click();
return false;
});
// Subscribe to messages coming in from the channel.
pubnub.subscribe({
channels: ['chat'],
message: handleMessage
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment