SmartCodingTips

Mouse & Keyboard Events in JavaScript

JavaScript makes it easy to react to user interaction with the mouse and keyboard. These events allow dynamic behavior like dragging, shortcuts, or interactivity in games and UI.

๐Ÿ–ฑ๏ธ Mouse Events

  • click โ€“ User clicks on an element
  • dblclick โ€“ Double click
  • mouseover / mouseout โ€“ Hover in/out
  • mousedown / mouseup โ€“ Press/release mouse button
  • mousemove โ€“ Mouse movement
document.getElementById("box").addEventListener("click", () => {
    alert("Box clicked!");
});

โŒจ๏ธ Keyboard Events

  • keydown โ€“ Key is pressed down
  • keyup โ€“ Key is released
  • keypress โ€“ (deprecated) Use keydown instead
document.addEventListener("keydown", function(event) {
    console.log("Key pressed:", event.key);
    if (event.key === "Enter") {
        alert("You pressed Enter!");
    }
});

๐Ÿ“Œ Accessing Event Data

document.addEventListener("click", function(e) {
    console.log("Mouse X:", e.clientX, "Mouse Y:", e.clientY);
});

๐Ÿงช Example With HTML

<input type="text" id="inputField" placeholder="Type something...">

<script>
document.getElementById("inputField").addEventListener("keyup", function(e) {
    console.log("You typed:", e.key);
});
</script>
๐Ÿ’ก Tip: Use event.preventDefault() if you want to stop default behavior like form submission.