page-hotkey
v1.0.2
Published
Quick call to window.addEventListener
Maintainers
Readme
Page Hotkey
pageHotkey is a utility function for handling keyboard shortcuts in web applications. It provides an easy way to bind functions to specific key combinations within a webpage, enhancing user interaction through keyboard events.
Installation
npm install page-hotkeyThen, import the pageHotkey function in your JavaScript code:
import pageHotkey from 'page-hotkey';Usage
pageHotkey takes two parameters:
hotkey: A string representing the desired key combination (e.g.,"ctrl+s","alt+p").fn: A callback function that will be executed when the specified hotkey is pressed.
The function returns another function which, when called, will remove the event listener, allowing for cleanup when the hotkey is no longer needed.
Example
Here is a basic example of how to use pageHotkey:
import pageHotkey from 'page-hotkey';
const unsubscribe = pageHotkey('ctrl+s', (e) => {
console.log('Save shortcut activated!');
// Add your save functionality here.
});
// To remove the hotkey listener when no longer needed:
unsubscribe();Functionality
- Prevent Default Behavior: By calling
e.preventDefault(), the default browser action for the hotkey is prevented. - Stop Propagation: The event propagation is stopped immediately with
e.stopImmediatePropagation(), ensuring that no other event listeners are triggered. - Abort Controller: Utilizes the AbortController API to manage event listener cleanup efficiently.
Benefits
- Ease of Use: Simplifies the process of setting up and removing keyboard shortcuts in web applications.
- Reusability: Designed to be reusable across various parts of an application.
- Performance: The usage of AbortController ensures that resources are not wasted on unused event listeners.
Notes
- Ensure that
hotkey-matcheris compatible with your desired key combinations. - Be careful when assigning hotkeys that might conflict with common browser shortcuts or accessibility features.
License
This utility is open source and available under the MIT License. Feel free to contribute or modify as per your needs.
