简体   繁体   中英

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(); }); 

You're not calling OnKeyEnterPressDoThis inside the keypress event listener, you're declaring the function. Move the function out of the event listener and call it when the event is called.

Also use e.keyCode instead of e.keyCode(); since keyCode it's not a function.

In some browsers e.keyCode is undefined, you have to use e.which in those cases.

So something like this should add a little of browser support:

var key = e.which || e.keyCode || 0;

Code:

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

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

    var key = e.which || e.keyCode || 0;

    if (key === 13) {
        OnKeyEnterPressDoThis();
    }

});

// Agregar Tarea
Btn_List.addEventListener("click", OnKeyEnterPressDoThis);

try e.which

 Btn_List.addEventListener("keypress" , function(e){ 
    var key = e.which;
                   alert(key)
 });
 Btn_List.addEventListener("click" , function(e){ 
      alert('ff') 
  });
  1. You should scan for e.which , since some browsers don't honor e.keyCode
  2. You should use e.preventDefault() because an enter on a button triggers a click event (for accessibility reasons)
  3. You should avoid using keypress and instead use the keydown or keyup events in order to avoid double-events (as mentioned in #2 above)

 var Btn_List = document.querySelector('button'); Btn_List.addEventListener("keydown", function(e) { var key = e.which && e.which || e.keyCode(); if (key !== 9) e.preventDefault(); // allow tab if (key === 13) { console.log('Enter pressed'); (function OnKeyEnterPressDoThis() { Input_Tarea(); showTheNmbrOfListElmts(); orderAlphaFukkabossList(); }()); } }); // Agregar Tarea Btn_List.addEventListener("click", function(e) { console.log(e.type); Input_Tarea(); showTheNmbrOfListElmts(); orderAlphaFukkabossList(); }); function Input_Tarea() { console.log('Input_Tarea'); } function showTheNmbrOfListElmts() { console.log('showTheNumbrOfListElmts'); } function orderAlphaFukkabossList() { console.log('orderAlphaFukkabossList'); } 
 <button>Click</button> <button onClick="console.clear()">clear console</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM