SyntaxStudy
Sign Up
JavaScript Beginner 7 min read

Mouse Events

Mouse Events

Mouse events fire in response to pointer device interactions. JavaScript distinguishes many types of mouse activity, allowing you to build interactive UIs that respond precisely to user intent.

click, dblclick, contextmenu

click fires when the primary button is pressed and released on an element. dblclick fires on two rapid clicks. contextmenu fires on right-click (or a long-press on touch), often used to create custom context menus by calling event.preventDefault().

mousedown, mouseup, mousemove

mousedown fires when a button is pressed, mouseup when released. Tracking both enables drag-and-drop. mousemove fires repeatedly as the pointer moves — use it sparingly and throttle with requestAnimationFrame or debounce to avoid performance issues.

mouseover, mouseout, mouseenter, mouseleave

mouseover and mouseout bubble — they fire when the pointer enters or leaves any descendant element too. mouseenter and mouseleave do not bubble and fire only for the element they are bound to.

Example
const box = document.querySelector('#box');
box.addEventListener('click', e => {
  console.log('click at', e.clientX, e.clientY);
});
box.addEventListener('dblclick', () => {
  console.log('double clicked');
});
box.addEventListener('contextmenu', e => {
  e.preventDefault();
  console.log('right-click blocked');
});
box.addEventListener('mouseenter', () => box.classList.add('hover'));
box.addEventListener('mouseleave', () => box.classList.remove('hover'));
box.addEventListener('mousedown', e => {
  console.log('button:', e.button); // 0=left, 1=mid, 2=right
});
Pro Tip

Prefer mouseenter/mouseleave over mouseover/mouseout for hover effects — they do not fire repeatedly when the mouse moves over child elements, preventing jitter and unnecessary state changes.