For accessibility, it is often needed to perform the same action on mouse-click and on pressing enter or space on the keyboard. What is the best way handle those events on a given element?
For example:
<div @click="doTheThing" @keyup.enter="doTheThing" tabindex="0">Do the Thing</div>
Is there a better way to call the the event handler without having the multiple listeners?
For accessibility, it is often needed to perform the same action on mouse-click and on pressing enter or space on the keyboard. What is the best way handle those events on a given element?
For example:
<div @click="doTheThing" @keyup.enter="doTheThing" tabindex="0">Do the Thing</div>
Is there a better way to call the the event handler without having the multiple listeners?
Share Improve this question edited Feb 8 at 10:06 Mark Rotteveel 109k226 gold badges155 silver badges219 bronze badges asked Feb 7 at 20:00 Peter HentgesPeter Hentges 354 bronze badges 2 |2 Answers
Reset to default 2A directive to the rescue:
Playground
<script setup>
const vAction = (el, {value}) => {
el.addEventListener('click', value);
el.addEventListener('keyup', e => e.key==='Enter' && value());
}
function doTheThing(){
alert('do the thing');
}
</script>
<template>
<div v-action="doTheThing" tabindex="0">Do the Thing</div>
</template>
The best way to handle these events on a specific element - is when the element is a button
.
It will handle click
event like @keyup.enter
and @keyup.space
.
And it will be harmonious with accessibility.
<script setup>
const click = () => {
alert('click');
}
</script>
<template>
<button @click="click">Button</button>
</template>
Example
@click
– vanblart Commented Feb 7 at 20:43