Skip to content

Instantly share code, notes, and snippets.

@jervert
Last active April 4, 2019 08:40
Show Gist options
  • Save jervert/0b5dbceba8d07298547ae22714804086 to your computer and use it in GitHub Desktop.
Save jervert/0b5dbceba8d07298547ae22714804086 to your computer and use it in GitHub Desktop.
<p role="link" tabindex="0" data-link>Link by role</p>
<p role="button" tabindex="0" data-button>Button by role</p>
<script>
const EVENT_CLICK = 'click';
const EVENT_KEYBOARD = 'keypress';
const EVENTS_CLICK = [EVENT_CLICK, EVENT_KEYBOARD];
const KEY_ENTER = 13;
const KEY_ESPACE = 32;
const KEYS_BUTTON = [KEY_ENTER, KEY_ESPACE];
const elementButton = document.querySelector('[data-button]');
const elementLink = document.querySelector('[data-link]');
const actionButton = (ev) => {
if (ev.type === EVENT_CLICK || KEYS_BUTTON.includes(ev.keyCode)) {
console.log(`${ev.type} triggered on button!`);
}
};
const actionLink = (ev) => {
if (ev.type === EVENT_CLICK || ev.keyCode === KEY_ENTER) {
console.log(`${ev.type} triggered on link!`);
}
};
EVENTS_CLICK.forEach(event => {
elementButton.addEventListener(event, actionButton);
elementLink.addEventListener(event, actionLink);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment