Quantcast
Viewing latest article 3
Browse Latest Browse All 3

Answer by Steve for Mouse position relative to div

Seeing as it's now 2021... for those looking to achieve it without JQuery, here is a demo.

const element = document.getElementById('img');const globalCursorLabel = document.getElementById('global-cursor-label');const imgCursorLabel = document.getElementById('img-cursor-label');const boundsLabel = document.getElementById('bounds-label');// Bounding rect infoconst imgBoundInfo = element.getBoundingClientRect();boundsLabel.textContent = `Bounding Rect Info: ${JSON.stringify(imgBoundInfo)}`;element.addEventListener('mousemove', (e) => {    // Mouse position    const globalCursor = { x: 0, y: 0 };    globalCursor.x = e.clientX;    globalCursor.y = e.clientY;    globalCursorLabel.textContent = `Global Position: [x: ${globalCursor.x}px, y: ${globalCursor.y}px]`;    // Position in image considering top left of image to be 0px, 0px    const imgCursor = { x: 0, y: 0 };    imgCursor.x = globalCursor.x - imgBoundInfo.left;    imgCursor.y = globalCursor.y - imgBoundInfo.top;    imgCursorLabel.textContent = `Img Position: [x: ${imgCursor.x}px, y: ${imgCursor.y}px]`;});
body {  display: flex;  flex-direction: column;}img {  margin-top: 20px;  margin-left: 20px;  height: 100px;  width: 150px;}
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><img id="img" src="https://www.placecage.com/300/200" alt="nick"/><label id="global-cursor-label">Hover over Nick</label><label id="img-cursor-label">Hover over Nick</label><label id="bounds-label"></label></body></html>

Viewing latest article 3
Browse Latest Browse All 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>