Mouse Events in JavaScript
Handle mouse events in JavaScript: click, dblclick, mousemove positions, enter and leave, buttons, right click and drag detection. Explanation and output.
This code needs a web page. Add the HTML elements it looks up by id, link the script, and open the page in a browser. Node has no document object. Add <button id="myButton"> and a sized <div id="myElement">.
1// Method 1: Click events2const button = document.getElementById('myButton');34button.addEventListener('click', function(e) {5 console.log('Clicked');6});78button.addEventListener('dblclick', function(e) {9 console.log('Double clicked');10});1112// Method 2: Mouse position13const element = document.getElementById('myElement');1415element.addEventListener('mousemove', function(e) {16 console.log('X:', e.clientX, 'Y:', e.clientY);17 console.log('Page X:', e.pageX, 'Page Y:', e.pageY);18 console.log('Offset X:', e.offsetX, 'Offset Y:', e.offsetY);19});2021// Method 3: Mouse enter/leave22element.addEventListener('mouseenter', function(e) {23 console.log('Mouse entered');24 e.target.style.backgroundColor = 'yellow';25});2627element.addEventListener('mouseleave', function(e) {28 console.log('Mouse left');29 e.target.style.backgroundColor = '';30});3132// Method 4: Mouse over/out (bubbles)33element.addEventListener('mouseover', function(e) {34 console.log('Mouse over');35});3637element.addEventListener('mouseout', function(e) {38 console.log('Mouse out');39});4041// Method 5: Mouse down/up42element.addEventListener('mousedown', function(e) {43 console.log('Mouse button pressed:', e.button);44 // 0: left, 1: middle, 2: right45});4647element.addEventListener('mouseup', function(e) {48 console.log('Mouse button released');49});5051// Method 6: Context menu (right click)52element.addEventListener('contextmenu', function(e) {53 e.preventDefault();54 console.log('Right click prevented');55 // Show custom context menu56});5758// Method 7: Mouse buttons59element.addEventListener('mousedown', function(e) {60 if (e.button === 0) {61 console.log('Left button');62 } else if (e.button === 1) {63 console.log('Middle button');64 } else if (e.button === 2) {65 console.log('Right button');66 }6768 // Check which buttons are pressed69 console.log('Buttons:', e.buttons);70 // 1: left, 2: right, 4: middle71});7273// Method 8: Drag detection74let isDragging = false;7576element.addEventListener('mousedown', function(e) {77 isDragging = true;78 console.log('Drag started');79});8081element.addEventListener('mousemove', function(e) {82 if (isDragging) {83 console.log('Dragging at:', e.clientX, e.clientY);84 }85});8687element.addEventListener('mouseup', function(e) {88 if (isDragging) {89 isDragging = false;90 console.log('Drag ended');91 }92});
Sample Output
Page Y: 485
pageY is larger than clientY because the page was scrolled down 400 pixels.
Buttons: 1
e.buttons uses 1 for left, 2 for right, 4 for middle.
In this one
- The main mouse event types
- The difference between client, page and offset positions
- Why mouseenter is better for hover than mouseover
- How to track a drag with a flag
How it works
- 1
click and dblclick listeners are added to the button.
- 2
mousemove logs three kinds of coordinates.
- 3
mouseenter colours the box and mouseleave clears it.
- 4
mousedown logs which button was pressed.
- 5
contextmenu prevents the right-click menu.
- 6
A flag tracks drag start, movement and end.
Edge cases
Double click also fires click
A dblclick logs Clicked twice first.
Browsers send two clicks, then dblclick. Use a short timer if you must tell them apart.
Releasing the mouse outside the element
mouseup never fires on the element, so isDragging stays true.
Listen for mouseup on document instead.
Too many mousemove logs
Logging on every move can slow the page.
Throttle the handler or use requestAnimationFrame.
What's going on
Mouse events tell your code what the pointer is doing. They power hover effects, click tracking, drawing apps and drag and drop.
The main types are click for a single click and dblclick for a double click. mousedown and mouseup fire when a button is pressed and released. mousemove fires many times as the mouse moves. mouseenter and mouseleave fire when the pointer enters or leaves an element. mouseover and mouseout are similar, but they bubble, so they also fire for child elements. contextmenu fires on right click.
Method 2 prints three kinds of position. clientX and clientY are measured from the visible window, the viewport. pageX and pageY are measured from the top of the whole document, so they include scrolling. offsetX and offsetY are measured from the element's own corner.
Method 3 uses mouseenter and mouseleave for a hover highlight. They are the better choice for hover because they do not fire again for every child element.
Method 5 reads e.button to see which button was pressed. 0 is left, 1 is middle, 2 is right. Method 7 also reads e.buttons, which lists all pressed buttons as a sum: 1 for left, 2 for right, 4 for middle. Note the order differs between button and buttons.
Method 6 blocks the browser menu on right click with preventDefault, so you can show your own menu.
Method 8 detects a drag with a flag. isDragging becomes true on mousedown. mousemove only logs while the flag is true. mouseup resets it. Tracking drag state with flags is a simple pattern you will use often.
Use cases include interactive UI, drag and drop, hover effects and click tracking.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which value of e.button means right click?
Pick an answer to check it.
Question 2
Which coordinates include page scrolling?
Pick an answer to check it.
Questions people ask
Why are there two hover pairs?
mouseover and mouseout bubble and fire for children. mouseenter and mouseleave do not.
Does this work on phones?
Taps send a click, but hover and drag need touch or pointer events.
What is e.buttons for?
It tells you which buttons are held during mousemove.