tickle/modules/utils/onDocumentKey.mjs
2023-05-09 04:00:53 +02:00

44 lines
868 B
JavaScript

//@ts-check
/**
*
* @param {string} keyToListen
* @param {()=>void} callback
*/
export const onDocumentKeyUp = (keyToListen, callback) => {
document.addEventListener(
"keyup",
({ key }) => key === keyToListen && callback()
);
};
/**
*
* @param {string} keyToListen
* @param {()=>void} callback
*/
export const onDocumentKeyDown = (keyToListen, callback) => {
document.addEventListener(
"keydown",
({ key }) => key === keyToListen && callback()
);
};
/**
*
* @param {string} keyToListen
* @param {(down:boolean)=>void} callback
*/
export const onDocumentKey = (keyToListen, callback) => {
document.addEventListener(
"keyup",
({ key }) => key === keyToListen && callback(false)
);
document.addEventListener(
"keydown",
({ key }) => key === keyToListen && callback(true)
);
};
export default onDocumentKey;