RickInWestPalmBeach
RickInWestPalmBeach

Reputation: 558

Detect Enter Key in Javascript with no Input fields

I am creating a custom notification popup, and I am trying to detect an Enter key in Javascript on a form that has no input fields.

I have tried adding "onkeypress" to my tag but this didn't work.

Any ideas?

Upvotes: 0

Views: 789

Answers (3)

mplungjan
mplungjan

Reputation: 178422

Like this

e.which is 13 on enter and e.target tells you where that happened

e.code is "Enter" but is less supported

window.addEventListener("keypress",function(e) { 
  console.log(e.target.tagName,e.which === 13) 
})
<form>
<input type="button">
</form>

Only on the form

document.getElementById("myForm").addEventListener("keypress",function(e) { 
  console.log(e.target.tagName,e.which === 13) 
})
<form id="myForm">
<input type="button">
</form>

In a div:

document.getElementById("popup").addEventListener("keypress", function(e) {
  console.log(e.target.tagName, e.target.closest("div").id, e.which === 13)
})
#popup {
  text-align: center;
  height: 100px;
  width: 100px;
  position: absolute;
  top: 100px;
  left: 100px;
  border:1px solid black;
  padding:20px;
}
<div id="popup">
  <form id="myForm">
    <input type="button">
  </form>
</div>

Upvotes: 2

Aya Mostafa
Aya Mostafa

Reputation: 34

document
  .querySelector("#my_form")
  .addEventListener("keypress", function(e) {
    console.log(e.target.tagName);
    if (e.code === "Enter") {
      console.log("hiii");
    }
  });
<form id="my_form" style="border: 1px solid red; outline: 0" tabindex="0">
  <label>....</label>
</form>

Upvotes: 1

RickInWestPalmBeach
RickInWestPalmBeach

Reputation: 558

Thank you for all the responses. I am quite sure, under normal circumstances, they would have worked. However, since my modal (which needed to detect a keypress) was display over a form (which also had a keypress), I had to add a modal status (visible/hidden) and edit the keypress of my main form based on the modal status.

function handleKeyPress(e)
{
    var key=e.keyCode || e.which;

    var modalstatus = $("#modalstatus").val();

    if (key==13)
    {
        if (modalstatus == "hidden")
            Event_On_Main_Page();
        else
            Modal_Event();
    }
}

Upvotes: 0

Related Questions