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 |
|
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
4button.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 | button.onclick = function(event) { |
Handle Mousemove Event
Handling mousemove event is very similar to mouse click event.
Example to handle mousemove event using onmousemove
function
1 | <div id="mydiv" style="width:500px;height:500px;background-color: aqua;"> |