JS — detect mouse coordinates

blossom0417
Sep 3, 2018 · 1 min read
  • have a look at ‘ev’ (mouse event)and how it works.
  • event.pageX
  • event.clientX
  • element.scrollLeft -Get the number of pixels scrolled
  • element.scrollTop
const getMousePos = function(ev) {
let posx = 0;
let posy = 0;
if (!ev) ev = window.event;
if (ev.pageX || ev.pageY) {
posx = ev.pageX;
posy = ev.pageY;
} else if (ev.clientX || ev.clientY) {
posx = ev.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
posy = ev.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
//console.log(posx)
return {
x: posx,
y: posy
};
};
//
// attach handler to the click event of the document
if (document.attachEvent) document.attachEvent('onclick', function(e) {
const ps = getMousePos(e);
console.log(ps.x)
});
else document.addEventListener('click', function(e) {
const ps = getMousePos(e);
console.log(getMousePos(e))
//console.log('ps.x =',ps.x, 'ps.y=',ps.y)
});

# add

  • element.offsetWidth, element.offsetHeight
    - returns the layout width of an element
    - width + padding + border (not including margin)
  • event.target.offsetX, event.offsetY
    - the offset in the X coordinate of the mouse pointer
    - relative to the target element.
  • event.clientX — according to the client area
    - The client area is the current window.
  • event.screenX -returns the horizontal coordinate (according to the users computer screen)
  • event.pageX
    — This property is non-standard, but works in most major browsers.
    - returns the horizontal coordinate (according to the document) of the mouse pointer

#references

https://developer.mozilla.org/en-US/docs/Web/API/Element

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade