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");
}
});
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.
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 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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With