@spithacode/input-manager
v1.0.4
Published
A package which abstract dealing with keyboard and mouse events for a given HTML element
Readme
@spithacode/input-manager
A lightweight and efficient input management system for handling keyboard and mouse inputs for any HTML element in web applications.
Features
- ⌨️ Keyboard input handling
- 🖱️ Mouse input management with position tracking
- 🎯 Event-based architecture
- 🔄 Real-time input state updates
- 📦 Modular and reusable design
- 🧹 Automatic cleanup and resource management
- 🎨 Works with any HTML element
Installation
Using pnpm:
pnpm add @spithacode/input-managerUsage
Basic Example
import { InputManager } from "@spithacode/input-manager";
// Initialize the input manager with any HTML element
const targetElement = document.getElementById("your-element");
const inputManager = new InputManager(targetElement);
// Check if a key is pressed
if (inputManager.isKeyPressed("ArrowRight")) {
// Handle right arrow key press
}
// Get mouse position relative to the element
const mousePos = inputManager.getMousePosition();
console.log(`Mouse position: x=${mousePos.x}, y=${mousePos.y}`);
// Check mouse button state
if (inputManager.isMouseButtonPressed(0)) {
// Left mouse button
// Handle left click
}
// Clean up when done
inputManager.destroy();API Reference
InputManager Class
The main class that handles all input management. Can be used with any HTML element such as div, canvas, section, or any other valid HTML element.
Constructor
constructor(element: HTMLElement)element: Any HTML element to attach input listeners to (div, canvas, section, etc.)
Methods
isKeyPressed(key: Key): boolean- Check if a specific key is currently pressed
- Returns
trueif the key is pressed,falseotherwise
isMouseButtonPressed(button: MouseButton): boolean- Check if a mouse button is pressed
- Button values: 0 (left), 1 (middle), 2 (right)
- Returns
trueif the button is pressed,falseotherwise
getMousePosition(): MousePosition- Get current mouse coordinates relative to the target element
- Returns
{ x: number, y: number }
reset(): void- Reset all input states
destroy(): void- Clean up event listeners and resources
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT © Spithacode
Author
- Spithacode
- Website: https://spithacode.com
