Javascript - Handle Mouse Event

Handle mouse event using javascript only

Common mouse events are

  • click
  • dblclick
  • mouseup
  • mousedown
  • mousemove

Handling Click Event

You can use button.onclick = function(event){...} to handle click event.

Example to handle the onclick event

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 <!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Test</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
<button id="button">Button</button>

<script>
document.addEventListener("DOMContentLoaded", function() {
button.onclick = function() {
console.log(`Clicked`)
}
});
</script>
</body>
</html>

Get Event Coordinate

You can also pass the event object to the hanlder. event object properties can be found in MouseEvent interface

To check the coordinate, you can use the following properties

  • clientX, clientY
  • pageX, pageY
  • screenX, screenY
    1
    2
    3
    4
    button.onclick = function(event) {
    console.log(`Clicked at clientX:${event.clientX} clientY:${event.clientY}`);
    console.log(`Clicked at pageX:${event.pageX} pageY:${event.pageY}`);
    }

Check Keys

You can use altKey property to check if Alt key is pressed. CtrlKey is similar.

1
2
3
4
5
6
7
8
9
10
11
button.onclick = function(event) {
if(event.altKey) {
console.log('Alt');
}
if(event.ctrlKey) {
console.log('Ctrl');
}
if(event.shiftKey) {
console.log('Shift');
}
}

Handle Mousemove Event

Handling mousemove event is very similar to mouse click event.

Example to handle mousemove event using onmousemove function

1
2
3
4
5
6
7
8
9
<div id="mydiv" style="width:500px;height:500px;background-color: aqua;">
<span id="coordinate"></span>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
mydiv.onmousemove= function(event) {
coordinate.innerHTML = `${event.clientX}, ${event.clientY}`
}
});