-2

I have forked this repl.it https://replit.com/@templates/Socketio-Chat-Template and am using it with a friend but having to press the 'send button every time I want to send a message feels unnatural, is there any way to make it so that pressing enter sends the text currently in the box, like most chat apps?

Jake
  • 19
  • 5
  • Does this answer your question? [Trigger a button click with JavaScript on the Enter key in a text box](https://stackoverflow.com/questions/155188/trigger-a-button-click-with-javascript-on-the-enter-key-in-a-text-box) – João Paiva Jun 21 '21 at 09:29

1 Answers1

2

You can use the function "addEventListener" that will activate the button when Enter Key is pressed. For instance, the code in JavaScript would be like this:

var sendMessage = document.getElementById("sendMessage"); // Here your text input element
sendMessage.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) { // 13 is the number of Enter key on keyboard
        event.preventDefault();
        document.getElementById("sendButton").click(); // Here your button 
    }
})
  • I am rather new to javascript so am a little confused as to where I put this, could you take a look at the linked program and give me an idea of where? – Jake Jun 21 '21 at 12:24
  • You should put this in the Script.js file since it is JavaScript code. – Joao Soares Jun 21 '21 at 13:04
  • Hm, I have done this and it doesn't seem to work. Pressing enter has no effect – Jake Jun 21 '21 at 13:09