Last active
March 27, 2019 08:42
-
-
Save w-jerome/e39d803128ab38eb720aff43d03cfb77 to your computer and use it in GitHub Desktop.
Javascript — Cursor position in element
This file contains hidden or 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> | |
| <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