Mouse click events

Pressing a mouse button also causes a number of events to fire.

The mouse click events are

mousedownfires when the button is pressed
mouseupfires when the button is released

"mousedown" and "mouseup" events are similar to "keydown" and "keyup". These will happen on the DOM nodes that are immediately below the mouse pointer when the event occurs.

After the "mouseup" event, a "click" event fires on the most specific node that contained both the press and the release of the button.

For example, if you press down the mouse button on one paragraph and then move the pointer to another paragraph and release the button, the "click" event will happen on the element that contains both those paragraphs. If two clicks happen close together, a "dblclick" (double-click) event fires, after the second click event.

To get information about the place where a mouse event happened, you can use its pageX and pageY properties, which contain the event's coordinates (in pixels) relative to the top-left corner of the document.

The following example adds a dot under your mouse pointer every time you click the document.

addEventListener("click", function(event) {
    vardot = document.createElement("div");
    dot.className = "dot"; = (event.pageX - 4) + "px"; = (event.pageY - 4) + "px";

The clientX and clientY properties are similar to pageX and pageY but it is relative to the part of the document that is currently scrolled into view. These can be useful when comparing mouse coordinates with the coordinates returned by getBoundingClientRect, which also returns viewport relative coordinates.

Related Tutorial
Follow Us #