Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  23] [ 2]  / answers: 1 / hits: 15652  / 12 Years ago, thu, april 26, 2012, 12:00:00

I create table, handlers hooked up mousemove.
But in top left point I get .offsetX.offsetY equals -5-5.
Why? I need 0.



<table cellpadding=0 
id=target
cellspacing=0
width=602
height=500
style=float:left;
position:relative;
background: url(/content/games/kamikaze2/back.jpg) no-repeat 0 0;>
<tbody>...
</tbody>
</table>

<script type=text/javascript>

$(#target).mousemove(function (event) {
var msg = Handler for .mousemove() called at ;
msg += event.offsetX + , + event.offsetY;
$(#log).append(<div> + msg + </div>);
});
</script>

More From » jquery

 Answers
0

More examples here: show-popup-on-mouse-location




Mouse coordinates within element


The most accurate way to get the mouse coordinates within an element (without scrollbars) relative to viewport is by calculating the difference between





const getMousePos = (evt) => {
const pos = evt.currentTarget.getBoundingClientRect();
return {
x: evt.clientX - pos.left,
y: evt.clientY - pos.top
};
};

document.querySelector(#target).addEventListener('mousemove', (evt) => {
const mPos = getMousePos(evt);
evt.currentTarget.textContent = `Mouse position x:${mPos.x} y:${mPos.y}`;
});

#target {
position: absolute;
left: 50px;
top: 20px;
width: 200px;
height: 100px;
background: #0bf;
transform: translate(20px, 30px); /* works even with translate */
}

<div id=target></div>

<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js></script>




Subtracting those values you can retrieve the exact mouse position, x:0, y:0 being the upper left corner of your element. Even if an element is CSS-transformed, i.e: transform: translate(-50%, -50%), the returned values are still correct.


[#85969] Wednesday, April 25, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingcarloe

Total Points: 677
Total Questions: 109
Total Answers: 96

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
irvingcarloe questions
Wed, Mar 31, 21, 00:00, 3 Years ago
Tue, Aug 4, 20, 00:00, 4 Years ago
Fri, Jul 3, 20, 00:00, 4 Years ago
;