Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Created April 24, 2014 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mojaray2k/11262042 to your computer and use it in GitHub Desktop.
Save mojaray2k/11262042 to your computer and use it in GitHub Desktop.
Get Mouse Coordinates in JavaScript. You can get the user's mouse coordinates in three distinct ways in JavaScript: Relative to the browser window, relative to the page, and relative to the entire screen. Let's see how we can do this in each case.
body {
font-family: Arial, sans-serif;
text-align: center;
padding-top: 20px;
color: #555;
height: 3000px;
}
h1 {
font-size: 1.5em;
}
output {
font-size: 45px;
color: darkblue;
position: fixed;
bottom: 20px;
left: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<h1>Click Anywhere to View Your Mouse Coordinates Relative to the Browser or iFrame Window. Test by scrolling down, too.</h1>
<output id="op">[coordinates will display here]</output>
</body>
</html>
var op = document.getElementById('op');
function showCoords(e){
op.innerHTML = 'clientX value: ' +
e.clientX + '<br>' +
'clientY value: ' +
e.clientY;
}
document.onclick = function (e) {
showCoords(e);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment