HomeJAVASCRIPTHow to handle mouse events?

How to handle mouse events?

In JavaScript, mouse events let you respond to user interactions with the mouse (clicks, movement, scrolling, etc.). You handle them by attaching event listeners to DOM elements.


✅ Common Mouse Events

  • click → Fired when the element is clicked.
  • dblclick → Fired on a double click.
  • mousedown → Fired when the mouse button is pressed down.
  • mouseup → Fired when the mouse button is released.
  • mousemove → Fired when the mouse moves over an element.
  • mouseover → Fired when the mouse enters an element (bubbles).
  • mouseout → Fired when the mouse leaves an element.
  • mouseenter → Like mouseover but does not bubble.
  • mouseleave → Like mouseout but does not bubble.
  • contextmenu → Fired on right-click (before the context menu appears).

✅ Example: Handling Mouse Events

<button id="btn">Click Me</button>
<div id="box" style="width:200px;height:200px;background:lightblue;"></div>

<script>
  const btn = document.getElementById("btn");
  const box = document.getElementById("box");

  // Click event
  btn.addEventListener("click", () => {
    alert("Button clicked!");
  });

  // Mouse over & out
  box.addEventListener("mouseover", () => {
    box.style.background = "lightgreen";
  });

  box.addEventListener("mouseout", () => {
    box.style.background = "lightblue";
  });

  // Mouse move
  box.addEventListener("mousemove", (event) => {
    console.log(`Mouse at: X=${event.clientX}, Y=${event.clientY}`);
  });
</script>

✅ Event Object Properties

Inside mouse event handlers, you can use the event object:

  • event.clientX, event.clientY → Position relative to viewport
  • event.pageX, event.pageY → Position relative to page
  • event.button → Which button was pressed (0 = left, 1 = middle, 2 = right)
  • event.altKey, event.ctrlKey, event.shiftKey → Modifier keys
  • event.target → Element that triggered the event

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *