Home > Blockchain >  how to add an Enter key event listener?
how to add an Enter key event listener?

Time:12-06

btnSend.addEventListener('click', async(event)=>{

    event.preventDefault()
    let userInput = txtInput.value;

let temp = `<div >
<span >${userInput}</span>
<img src="static/img/me.jpeg" >
</div>`;

chatWindow.insertAdjacentHTML("beforeend", temp);
txtInput.value = ''
    scrollSmoothlyToBottom()
    txtInput.value = '';

   const botResponse = await chatBotChat(userInput)

                    let tempBot = `<div >
                    <img src="static/img/bot.jpeg" >
                    <span >${botResponse}</span>
                    </div>`;

                    chatWindow.insertAdjacentHTML("beforeend", tempBot);
                     scrollSmoothlyToBottom()

})

this is from my .html file

<form  action="">
        <div >Virtual Assitant</div>
        <div >!</div>
        <div  id="chat-window">
            <div >
                <img src="{{ url_for('static', filename='img/bot.jpeg')}}" alt="" >
                <span >Hi, How can i help you?</span>
            </div>
            <p id="scrollv"></p>
        </div>

        <div  id="input-area">
            <input autocomplete="off" type="text" name="msg" id="txtInput"/>
            <button id="btn-emoji">&#127773;</button>
            <button > <i >send</i></button>
        </div>
    </form>

How should i add an enter key listerner to this code?

I could only send a message by clicking on the submit button. Thanks for the help. im a beginner.

CodePudding user response:

Hope this helps to you.

document.onkeydown = (event) => {
    if (event.key === "Enter") {
      //Add your Enter event code here, like this.
      alert('Hi, Insert what you want to run here');
    }
}

CodePudding user response:

document.body.addEventListener("keydown", (e) => {
  if (e.key === "Enter") {
    //do stuff here
  } else {
    //do other stuff here
  }
});

you could also set the type attribute of the button to "submit" and it would run when you press enter

  • Related