JavaScript Mouse Events

In this article, you will learn about the mouse events and its associative properties and how JavaScript handles mouse events.

Here is the table of events related to mouse.

Mouse events Description
click Press a button element
dblclick Double click a button element
mousedown Press the mouse button
mouseup Release the mouse button
mousemove Mouse pointer moved
from one location to another
mouseleaveWhen mouse pointer
move away from HTML element
mouseenterWhen mouse pointer move onto
an html element

Mouse Event Properties

Mouse Event Properties Description
buttonReturn which button
was pressed
client X and clientYCoordinates relative to the
view port
( the visible part of the document)
pageX and clientYCoordinates relative to the
actual document page.
screenX and screenYCoordinates relative
to the screen
altKey, ctrlKey, shiftkeyReturn boolean true or false
when alt, shift or
ctrl key is pressed.

clientX and clientY

<body>
<p>clientX:<span id="cx">X</span></p>
<p>clientY:<span id="cy">Y</span></p>
<script>

     var s = document.getElementById("cx");
     var d = document.getElementById("cy");

     window.addEventListener('mousemove',processMove);
     window.addEventListener('mousemove',processMove);
     function processMove(evt){
          s.innerHTML = evt.clientX;
          d.innerHTML = evt.clientY;
     }
</script>
</body>

pageX and pageY

var s = document.getElementById("cx");
var d = document.getElementById("cy");
window.addEventListener('mousemove',processMove);
window.addEventListener('mousemove',processMove);
function processMove(evt){
     s.innerHTML = evt.pageX;
     d.innerHTML = evt.pageY;

AltKey and ShiftKey

<body>
<p>AltKey :<span id="altt"></span></p>
<p>ShiftKey :<span id="shiftt"></span></p>
<script>
     window.onkeydown = pressSpecial;
     var d = document.getElementById("altt");
     var s = document.getElementById("shiftt");

     function pressSpecial(evt)
     {
          d.innerHTML = evt.altKey;
          s.innerHTML = evt.shiftKey;
     }
</script>
</body>

In the example above, whenever user press the ctrl, shift key, it is displayed in the HTML

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag