Problem Statement Write a JavaScript program that prints the mouse coordinates in a text area when the mouse cursor is moved over the HTML document.
Expected Output
Solution
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Track mouse coordinates</title>
</head>
<body>
<div style="background-color:#8F9779;height:30px;">
</div>
<script type="text/javascript">
var mie = (navigator.appName == "Microsoft Internet Explorer") ? true : false;
if(!mie){
document.captureEvents(Event.MOUSEMOVE);
}
document.onmousemove = mousePos;
var mouseX = 0;
var mouseY = 0;
function mousePos(e){
if(!mie){
mouseX = e.pageX;
mouseY = e.pageY;
}
else{
mouseX = e.clientX + document.body.scrollLeft;
mouseY = e.clientY + document.body.scrollRight;
}
/*document.write clears the document and all the event handlers inside it*/
document.body.innerHTML += "X: " + mouseX + ";Y: " + mouseY + "; Time: " + new Date() + "<br>";
return true;
}
</script>
</body>
</html>
Above code is written using deprecated API captureEvents
.MDN says, captureEvents
is deprecated.
Code still works fine with this deprecated API.
Can this code be improved, by replacing captureEvents
with a better standard API?