Emmanuel Ruiz Emmanuel Ruiz - 7 months ago 38
Javascript Question

Trigger an event on click or when enter key is pressed [JavaScript]

I wrote this code and only the click event is working, but key event doesn't. Can anyone explain to me why?



Btn_List.addEventListener("keypress", function(e) {

var key = e.keyCode();

if (key === 13) {

function OnKeyEnterPressDoThis() {
Input_Tarea();
showTheNmbrOfListElmts();
orderAlphaFukkabossList();
}

}

});

// Agregar Tarea
Btn_List.addEventListener("click", function() {
Input_Tarea();
showTheNmbrOfListElmts();
orderAlphaFukkabossList();
});




Answer Source

When registering key events register then on document, or <input>. Try clicking the BUTTON, typing in the <input>, and click the ENTER key anywhere in the snippet (i.e. document).

Snippet

document.getElementById('button1').onclick = testCallback;

document.getElementById('text1').addEventListener("keyup", testCallback, false);


document.addEventListener("keypress", function(e) {
  var key = e.keyCode;
  if (key === 13) {
    testCallback(e);
  }
}, false);



function testCallback(e) {
  var currEvent = null;
  currEvent = e.type;
  document.getElementById("display1").innerHTML = currEvent;
}
output {
  display: block;
  margin: 50px auto;
  width:100%;
}
<input id='button1' type='button' value='BUTTON'>

<input id='text1'>

<output id='display1' name='display1'></output>