Reputation: 481
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");
}
});
Upvotes: 9
Views: 13292
Reputation: 3
I thinks this is the best answer
<form>
<input id="myInput" placeholder="Some text.." value="">
<input type="submit" id="myBtn" value="Submit">
</form>
<script>
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click();
}
});
</script>
Upvotes: -1
Reputation: 89139
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>
Upvotes: 5
Reputation: 7336
No, you need to use two listeners, but as you have to pass a function to the listener which is called and gets all the necessary arguments you can create a single function for both cases like this:
function handleEvent(e){
if(e //make sure a mouseEvent has been passed as argument
&&
e.keyCode === 13 //check for the correct key
){
console.log("click");
}
}
document.getElementById("myId").addEventListener("click", handleEvent);
document.getElementById("myId").addEventListener("keyup", handleEvent);
Upvotes: 1