Skip to content

Instantly share code, notes, and snippets.

@w-jerome
Last active March 27, 2019 08:42
Show Gist options
  • Select an option

  • Save w-jerome/e39d803128ab38eb720aff43d03cfb77 to your computer and use it in GitHub Desktop.

Select an option

Save w-jerome/e39d803128ab38eb720aff43d03cfb77 to your computer and use it in GitHub Desktop.
Javascript — Cursor position in element
<!doctype html>
<html>
<head>
<style>
html {
background: #aaf;
}
body {
margin: 0;
}
div {
margin: 4em;
height: 300px;
background: #faa;
}
</style>
</head>
<body>
<div></div>
<span></span>
<script>
// https://atomiks.github.io/30-seconds-of-css/
var div = document.querySelector('div')
var span = document.querySelector('span')
div.onmousemove = function (e) {
var x = e.pageX - div.offsetLeft
var y = e.pageY - div.offsetTop
//If the element's parent has a positioning context (position: relative), you will need to subtract its offsets as well.
//var x = e.pageX - div.offsetLeft - div.offsetParent.offsetLeft
//var y = e.pageY - div.offsetTop - div.offsetParent.offsetTop
span.innerHTML = x + 'px - ' + y + 'px'
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment