Created
August 9, 2018 13:13
-
-
Save kebman/42598fe101f30ca5c8bd495b20afbbe9 to your computer and use it in GitHub Desktop.
Short HTML5 + JavaScript that tracks mouse position only while the mouse button is clicked down
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Track Mouse Position II</title> | |
<meta charset="utf-8"> | |
<style type="text/css"></style> | |
</head> | |
<body> | |
<header> | |
<h1>Track Mouse Position II</h1> | |
</header> | |
<section> | |
<article> | |
<h1>Position Data</h1> | |
<p>Click mouse and hold.</p> | |
<div id="client"></div> | |
<div id="screen"></div> | |
</article> | |
</section> | |
<footer></footer> | |
</body> | |
</html> | |
<script type="text/javascript"> | |
const client = document.getElementById("client"); | |
const screen = document.getElementById("screen"); | |
function mousePos(e) { | |
let cX = e.clientX, cY = e.clientY; | |
let sX = e.screenX, sY = e.screenY; | |
return { | |
coords1: "client - X: " + cX + ", Y coords: " + cY, | |
coords2: "screen - X: " + sX + ", Y coords: " + sY | |
} | |
} | |
let mousedown = false; | |
window.addEventListener('mousedown', (e)=>{ | |
mousedown = true; | |
client.innerHTML = mousePos(e).coords1; | |
screen.innerHTML = mousePos(e).coords2; | |
}, false); | |
window.addEventListener('mouseup', (e)=>{ | |
mousedown = false; | |
client.innerHTML = ""; | |
screen.innerHTML = ""; | |
}, false); | |
window.addEventListener('mousemove', (e)=>{ | |
if (mousedown) { | |
client.innerHTML = mousePos(e).coords1; | |
screen.innerHTML = mousePos(e).coords2; | |
} | |
}, false); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment