I have a working chat system, but when people spam the chat, the chat get longer and the page gets longer and very laggy. How do i remove the messages on the top?
My JavaScript so far:
let username = "Community Bot";
let chatMsg = ["Hello! Welcome to this game. Please press 'i' for instructions!"];
function appendChatMessage(currentUserName, chatMessage) {
let chatElem = document.createElement("p");
chatElem.innerHTML = "<strong>" currentUserName ": </strong>" chatMessage;
document.querySelector(".chat").appendChild(chatElem);
}
for (let i = 0; i < chatMsg.length; i ) {
appendChatMessage(username, chatMsg[i])
}
let Game = {
currentGame: {
variables: {
Clicks: 0,
Increment: 1,
sendMessage: function(messageContent) {
chatMsg.push(messageContent);
appendChatMessage(username, messageContent);
document.querySelector(".enterT").innerHTML = ""
}
}
}
}
My HTML so far:
<div >
<h1>
CHAT
</h1>
</div>
<div>
<input type="text" placeholder="Enter A Message..!"><button
onclick="Game.currentGame.variables.sendMessage(document.querySelector('.enterT').value)">send
message</button>
</div>
CodePudding user response:
You can check the below implementation
I moved <h1>CHAT</h1>
out of <div ></div>
for only keeping chat message in <div ></div>
let username = "Community Bot";
let chatMsg = ["Hello! Welcome to this game. Please press 'i' for instructions!"];
function appendChatMessage(currentUserName, chatMessage) {
let chatElem = document.createElement("p");
chatElem.innerHTML = "<strong>" currentUserName ": </strong>" chatMessage;
document.querySelector(".chat").appendChild(chatElem);
document.querySelector(".enterT").value = ""
}
for (let i = 0; i < chatMsg.length; i ) {
appendChatMessage(username, chatMsg[i])
}
let Game = {
currentGame: {
variables: {
Clicks: 0,
Increment: 1,
sendMessage: function(messageContent) {
if (!messageContent) {
return
}
chatMsg.push(messageContent);
appendChatMessage(username, messageContent);
},
deleteTopMessage: function() {
const chatElement = document.querySelector(".chat")
if (chatElement.children[0]) {
chatElement.removeChild(chatElement.children[0])
}
if (chatMsg.length > 0) {
chatMsg.shift()
}
}
}
}
}
<h1>
CHAT
</h1>
<div >
</div>
<div>
<input type="text" placeholder="Enter A Message..!">
<button onclick="Game.currentGame.variables.sendMessage(document.querySelector('.enterT').value)">send
message</button>
<button onclick="Game.currentGame.variables.deleteTopMessage()">delete top message</button>
</div>
CodePudding user response:
Maybe have all your messages in an array and remove them with .pop or .shift?