E.pageX and e.pageY not working correctly?

I am trying to place a div wherever the cursor is on a mouse click. Therefore, when I use e.PageX and e.pageY, it actually makes my div much lower than expected. Any ideas?

var mouseX = e.pageX; var mouseY = e.pageY; $("#moverdiv").css({'top':mouseY,'left':mouseX}); 
+4
source share
2 answers

This works for me. Try the following:

 <!DOCTYPE html> <html> <head> <script src="jquery.js"></script> <script> $(document).ready(function(){ $(document).click(function(e){ var mouseX = e.pageX; var mouseY = e.pageY; $("#moverdiv").css({'top':mouseY, 'left':mouseX}); }); }); </script> <style type="text/css"> #moverdiv{ position: absolute; top: 0px; left: 0px; background-color: #000; width: 100px; height: 100px; } </style> </head> <body> <div id="moverdiv"></div> </body> </html> 

And this is a demo

+3
source

Definition of pageX:

pageX is the integer value in pixels for the X coordinate of the mouse pointer relative to the entire document when the mouse event is triggered. This property allows for any horizontal page scrolling.

If you put this code:

  $(document.body).click(function(mouseEvent) { $("#MyDiv").css({ 'top': mouseEvent.pageY, 'left':mouseEvent.pageX }); }); 

It works great.

If the div is not in the desired position, it means that your DIV may have a repetition point different from the body (different from the upper left corner of the browser).

Indeed, an element with absolute positioning refers to the first source parent element. If the source parent is not found, the destination source parent is body . Perhaps you have an intermediate element with the CSS: position: relative property. This CSS property makes the element a reference for positioning and inducing a shift.

+4
source

Source: https://habr.com/ru/post/1437707/


All Articles