Home > database >  How do i make it so that the chat autmatically updates when the user send a message?
How do i make it so that the chat autmatically updates when the user send a message?

Time:04-03

I am trying to make a chat, that functions noramlly. As you can see here, i have some code that should output some text from a bot, then you can type into a textbox then press the "send" button to send text and it should automatically show up in the chat. I don't know why it is not appearing!

Please help thank you:)

Javascript:

let chatMsg = ["Hello! Welcome to this game. Please press 'i' for instructions!"];

let Game = {
  currentGame:{
    variables:{
      sendMessage:function(messageContent) {
        chatMsg.push(messageContent)
      }
    }
  }
}

let username = "CommunityBot";


for (let i = 0; i < chatMsg.length; i  ) {
  
  let chatElem = document.createElement("p");

  chatElem.innerHTML = "<strong>" username ": </strong>" chatMsg[i];
  
  document.querySelector(".chat").appendChild(chatElem);
}

HTML:

<div >
          <h1>
            CHAT

          </h1>

        </div>
        <div>
          <input  type="text" placeholder="Enter A Message..!"><button onclick="Game.currentGame.variables.sendMessage(document.querySelector('.enterT').innerHTML)">send message</button>
        </div>

Kevin

CodePudding user response:

You have 2 small problems with your code.

Firstly, your input value should be accessed by .value instead of .innerHTML

document.querySelector('.enterT').innerHTML

To

document.querySelector('.enterT').value

Secondly, you only call chatMsg.push(messageContent) but don't update document after you update input value.

let chatMsg = ["Hello! Welcome to this game. Please press 'i' for instructions!"];

//the function to support adding message to the document
function appendChatMessage(currentUserName, chatMessage) {
  let chatElem = document.createElement("p");
  chatElem.innerHTML = "<strong>"   currentUserName   ": </strong>"   chatMessage;
  document.querySelector(".chat").appendChild(chatElem);
}

let username = "CommunityBot";
for (let i = 0; i < chatMsg.length; i  ) {
  appendChatMessage(username, chatMsg[i])
}

let Game = {
  currentGame: {
    variables: {
      sendMessage: function(messageContent) {
        chatMsg.push(messageContent);
        //update your message in the document
        appendChatMessage(username, messageContent);
      }
    }
  }
}
<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>

  • Related