Friday, January 23, 2009

Capturing MouseEvents Using JavaScript

Capturing Mouse Events Using JavaScript :


Sometime there is a need to disable MouseEvents for specific task(s) in Web-Pages.

The following code-snippet shows how to achieve the same :


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Capturing Mouse Events Using JavaScript</title>
</head>
<body>
<div>
<b> Testing with Link Button : </b>
<a href="javascript:void(null)"
onmousedown="return captureButton(event)" onmouseup="return preventOperation(event)"
onclick="return preventOperation(event)" ondblclick="return preventOperation(event)"
oncontextmenu="return preventOperation(event)"
>Click here with various mouse buttons to test</a>
</div>
<br/>
<div>
<b> Testing wuth Submit Button : </b>
<input name=btnG type=submit onmousedown="return captureButton(event)" onmouseup="return preventOperation(event)"
onclick="return preventOperation(event)" ondblclick="return preventOperation(event)"
oncontextmenu="return preventOperation(event)">
</div>
<br/>
<div>
<b> Testing with Input Text : </b>
<input name=btnG type=text onmousedown="return captureButton(event)" onmouseup="return preventOperation(event)"
onclick="return preventOperation(event)" ondblclick="return preventOperation(event)"
oncontextmenu="return preventOperation(event)">
</div>

<script language="Javascript">
function captureButton(event)
{
var button;
if (event.which == null)
button= (event.button < 2) ? "MOUSE BUTTON : LEFT" :
((event.button == 4) ? "MOUSE BUTTON : MIDDLE" : "MOUSE BUTTON : RIGHT");
else
button= (event.which < 2) ? "MOUSE BUTTON : LEFT" :
((event.which == 2) ? "MOUSE BUTTON : MIDDLE" : "MOUSE BUTTON : RIGHT");
alert(button);
preventOperation(event);
}
function preventOperation(event)
{
if (event.preventDefault)
event.preventDefault();
else
event.returnValue= false;
return false;
}
</script>

</body>
</html>



Copy paste above code in a text document and named it as MouseEvents.html
Now test the same.

No comments:

Post a Comment