Caspert Caspert - 1 year ago 72
CSS Question

Why does the clientX and Y change on scroll?

I created a shape that follows your mouse x and y coordinates on mouse movement. You can check the result here:

This will work fine and the shape is in the center of your mouse cursor. Unfortunately I have some problems with it.

As you can see in the demo I have one section and that is positioned at the top of the screen. At the very top of of the HTML markup you will notice a comment out section. If you remove the comment markup, a new section is set. When you hover over the items, the result is the same as before, but when you scroll to the next section - that one with the three thumbs, you will notice that the shape is not centered to the mouse, it's way offset. Only when you hover over the bottom, you will see a little piece of the shape.

To center the circle to the center of the mouse cursor I use the following script:

var target = $(this);
var dot = target.find('.pointer');

var height = dot.height();
var width = dot.width();

var offset = target.offset();
var top =;
var left = offset.left;

var mX = (event.clientX - left) - width / 2;
var mY = (event.clientY - top) - height / 2;

Above code is from the mouseMove function, that will be triggered on mouse movement.

My question is what I do wrong of is missing in my code. When there is just one section it works as it should works, but after adding another section to the HTML markup, it will be messed up.

I looking forward to your responses. Hope there is some solution for that!

Answer Source

pageX and pageY:

Relative to the top left of the fully rendered content area in the browser. This reference point is below the url bar and back button in the upper left. This point could be anywhere in the browser window and can actually change location if there are embedded scrollable pages embedded within pages and the user moves a scrollbar.

So use pageX and pageY instead of clientX/Y:

  var mX = (event.pageX - left) - width / 2;
  var mY = (event.pageY - top) - height / 2;

for more detail read difference between clientX/Y and pageX/Y?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download