Programming Tutorials

How To Handle Mouse Event In JavaScript

Pinterest LinkedIn Tumblr

There are quite few mouse-related events. Pressing a mouse button causes a number of events to fire. The “mousedown” and “mouseup” events fire when the button is pressed and released. 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. If two clicks happen close together, a “dblclick” (double-click) event also fires, after the second click event. Click events on links and submit buttons have default actions that can be prevented using a mouse event handler.

Also Read: How To Handle Document Load Event in JavaScript

How To Handle MouseOver and MouseOut Event

Events of types mouseover (and mouseout) occur when a mouse comes over(goes out) an element. These two events can be used, among other things, to create hover effects, showing or styling something when the mouse is over a given element.

CSS code:

#button {
width: 186px;
height: 52px;
font-size:1em;
color:red;
}

HTML Code:

<button id="button">Mouse Over Me</button>

JavaScript Code:

<script>
var btn=document.getElementById("button")

if (btn.addEventListener) {

btn.addEventListener("mouseover", function(event) {
btn.style.background = "#00aaff";
btn.innerHTML="Mouse Over"; });

btn.addEventListener("mouseout", function(event) {
btn.style.background = "";
btn.innerHTML="Mouse Out";});
}

else if (btn.attachEvent) {

btn.attachEvent("onmouseover", function(event) {
btn.style.background = "#00aaff";
btn.innerHTML="Mouse OVer";});

btn.attachEvent("onmouseout", function(event) {
btn.style.background = "";
btn.innerHTML="Mouse Out"; });
}
</script>

Preview:

Also Read: How To Change The ClassName Using JavaScript

How To Handle MouseMove Event

Every time the mouse pointer moves, a “mousemove” event fires. This event can be used to track the position of the mouse. A common situation in which this is useful is when implementing some form of mouse-dragging functionality.

The object passed to mouse event handlers has clientX and clientY properties that specify the coordinates of the mouse pointer relative to the containing window. If you scroll down, left or up without moving the mouse the values of clientX/clientY don’t change, because they are relative to the window, not the document.

Here is an example to show changes the value of clientX and clientY property on move the mouse over the input.

<input onmousemove="this.value = event.clientX+':'+event.clientY">

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

Here is an example to show changes the value of pageX and pageY property on move the mouse over the input.

<input onmousemove="this.value = event.pageX+':'+event.pageY">

Preview:

Following is the preview of above HTML codes, changes the value of clientX and clientY property on move the mouse over the input.

Here is another example to show the mousemove event, where width and height of rectangle changes on mousemove.

HTML Code:

<p>Drag the bar to change its width:</p>
<div id="div1" style="background: green; width: 60px; height: 20px">
</div>

JavaScript Code:

<script> var lastX; var lastY;
var rect = document.getElementById("div1");
rect.addEventListener("mousedown", function(event) {
if (event.which == 1) {
lastX = event.pageX;
lastY=event.pageY;
addEventListener("mousemove", moved);
event.preventDefault();
} });
function buttonPressed(event) {
if (event.buttons == null) return event.which != 0;
else return event.buttons != 0;
}
function moved(event) {
if (!buttonPressed(event)) {
removeEventListener("mousemove", moved);
}
else {
var distX = event.pageX - lastX;
var distY=event.pageY-lastY;
var newWidth = Math.max(10, rect.offsetWidth + distX);
var newHeight = Math.max(10, rect.offsetHeight + distY);
rect.style.width = newWidth + "px";
rect.style.height = newHeight + "px";
lastX = event.pageX;
lastY = event.pageY;
} }
</script>

Preview:

Drag the bar to change its width and height:

Drag the bar to change its width:

Read Also: How To Register Event Handlers in JavaScript

How To Handle Click and Double Click Event

For click-related mouse events, it may be important, which button was pressed. The button property specifies which mouse button, if any, was held down when the event occurred. The event object contains two properties which and button, they store the button in a numeric form.

Most of the browsers except IE have which value 0 for left button pressed, 1 for middle button pressed and 2 for right button pressed. For IE browser, the property button property is a 3-bit number, every bit is up if the button is pressed.So, button & 1 is set to 1, if the left button is pressed, button & 2 is 1, if the right button is pressed, and button & 4 if the middle button is pressed.

HTML Code:

<div id="which-button" style="width:300px;height:50px;border:solid brown 1px;font-size=1.5em;color:red;text-align:center;padding-top:20px;">Press Left, Middle or Right button<div>

JavaScript Code:

<script>
var wh=document.getElementById('which-button');
document.onclick=function(e) {
if (!e.which && e.button) {
if (e.button & 1) e.which = 1      // Left
else if (e.button & 4) e.which = 2 // Middle
else if (e.button & 2) e.which = 3 // Right
}
if (e.which==1) {wh.innerHTML="Left Button Pressed";}
else if (e.which==2) {wh.innerHTML="Middle Button Pressed";}
else if (e.which==3) {wh.innerHTML="Right Button Pressed";}
}
</script>

Preview:

Press left, middle or right button to see which mouse button was pressed.

Press Left, Middle or Right button

The following code implements a primitive drawing program. Every time you click the document, it adds a dot under your mouse pointer.

CSS Code:

<style>
.disc {
height: 8px; width: 8px; border-radius: 20px; border:solid red 14px;
background: blue; position: absolute;
}
</style>

JavaScript Code:

<script>
var place=document.getElementById("placeholder")
place.addEventListener("click", function(event) {
if (event.which==1){
var disc = document.createElement("div");
disc.className = "disc";
disc.style.left = (event.pageX - 15) + "px";
disc.style.top = (event.pageY - 15) + "px";
place.appendChild(disc); }
});
</script>

HTML Code

<p id="placeholder" style="height:35px; width:100%; border:solid blue 2px;"></p>

Preview:

Left click on the area of rectangle to see the effect of mouse click, which draws a red disc with blue dot on center point.

The context menu event usually signals a right-button click, but it may be impossible to prevent the appearance of a context menu when this event occurs.

Here is an example code for displaying alert message on right click instead of displaying context menu. Using this technique, you can create custom context menu instead of default.

HTML Code:

<input type="button" oncontextmenu="alert('Custom menu');return false" value="Right-click me"/>

Read Next:How To Handle Keyboard Event In JavaScript

Author

Shuseel Baral is a web programmer and the founder of InfoTechSite has over 8 years of experience in software development, internet, SEO, blogging and marketing digital products and services is passionate about exceeding your expectations.

Comments are closed.