Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining mouse click and enter key press in the same event listener

Tags:

javascript

I have a div that I made focusable with tabindex, and I want it to act like a button, doing something on both mouse click and enter key press. Can you do this with a single event listener, combining the following into one?

document.getElementById("myId").addEventListener("click", function() {
    console.log("click");
});
document.getElementById("myId").addEventListener("keyup", function(e) {
    if(e.keyCode === 13) {
        console.log("click");
    }
});
like image 992
Zebrastian Avatar asked Aug 10 '18 17:08

Zebrastian


People also ask

Can you add two functions to an event listener?

We can invoke multiple functions on a single event listener without overwriting each other. To do this we simply call the addEventListener() method more than once with a different function. In the example above, we add another event listener for the same event on the same button.

How do you trigger click event on pressing Enter key?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.

Can you add two event listeners to the same button?

Can you add multiple event listeners to a button? We can add multiple event listeners for different events on the same element. One will not replace or overwrite another. In the example above we add two extra events to the 'button' element, mouseover and mouseout.


1 Answers

You can put the events to handle in an Array and use forEach to add the event listener to the element.

<div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div>
<script>
var div = document.querySelector('div');
["click", "keypress"].forEach(ev=>{
  div.addEventListener(ev, function(e){
     if(ev=="click"){
       console.log("click");//clicked
     }
     if(e.keyCode==13){
      console.log("click");//enter key pressed
     }
  });
});
</script>

You can also define a function that both of the event listeners call.

<div tabindex="-1" style="width: 100px; height: 100px; border: 1px solid black; background-color: #f0f"></div>
<script>
var div = document.querySelector('div');
["click", "keypress"].forEach(ev=>{
  div.addEventListener(ev, handleEvent);
});
function handleEvent(e){
 if(e.type=="click"){
    console.log("click");//clicked
  }
  if(e.keyCode==13){
   console.log("click");//enter key pressed
  }
}
</script>
like image 88
Unmitigated Avatar answered Oct 02 '22 01:10

Unmitigated