Skip to content
Permalink
5275a9f770
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
84 lines (68 sloc) 2.63 KB
// Register a service worker, this one located in serviceworker.js
// A service worker is a piece of code the browser runs behind the scenes.
if ('serviceWorker' in navigator) {
console.log('CLIENT: service worker registration in progress.');
navigator.serviceWorker.register('sw.js').then(function() {
console.log('CLIENT: service worker registration complete.');
}, function() {
console.log('CLIENT: service worker registration failure.');
});
} else {
console.log('CLIENT: service workers are not supported.');
}
let allMessages = [];
let chatBox = document.querySelector("#chatBox");
let newMsgInput = document.querySelector("#newMsg");
let userName = localStorage.getItem('userName') || "me";
let notifSound = 'for-sure.mp3';
let notifSoundElement = new Audio(notifSound);
let usernameInput = document.querySelector("#usernameInput");
usernameInput.innerHTML = userName;
function clearChatInput() {
document.querySelector("#newMsg").value = "";
document.querySelector("#newMsg").focus();
}
function displayNewMessage(msg) {
var newMsgP = document.createElement("p");
newMsgP.innerHTML = "<strong>" + msg.sentBy + "</strong>: " + msg.message;
chatBox.appendChild(newMsgP);
window.navigator.vibrate(200);
notifSoundElement.play();
clearChatInput();
}
function makeNewMessageFromLocalUser() {
let usrMsg = {
sentBy: userName,
dateStamp: Date.now(),
message: newMsgInput.value
}
if(usrMsg.message !== "") {
allMessages.push(usrMsg);
// end make message
displayNewMessage(usrMsg)
}
}
//** All the triggers and event listener assignments down here... */
// assign the "Make New Message" function to the button click
document.querySelector("#sendBtn").addEventListener('click', function(){
makeNewMessageFromLocalUser()
});
// since we're not using a real form, assign it to the "keyup return" of the message input too
document.querySelector("#newMsg").addEventListener('keyup', function(e) {
if (e.keyCode === 13) {
makeNewMessageFromLocalUser();
}
});
// when username input is changed, update localstorage and global variable
usernameInput.addEventListener('blur', function() {
var oldUsername = localStorage.getItem("userName");
var newUsername = this.innerHTML;
var alertNew = {
sentBy: "system",
dateStamp: Date.now(),
message: `${oldUsername} has changed their name to ${newUsername}`
}
displayNewMessage(alertNew);
localStorage.setItem("userName", newUsername);
userName = localStorage.getItem("userName");
});