7

I'm trying to place a div wherever the cursor is when the mouse is clicked. So when I use e.PageX and e.pageY, it's actually placing my div far lower than intended. Any ideas?

var mouseX = e.pageX;
var mouseY = e.pageY;
$("#moverdiv").css({'top':mouseY,'left':mouseX});
Mike
  • 980
  • 3
  • 15
  • 29
  • What is the positioning of `#moverdiv`? – Musa Oct 04 '12 at 00:20
  • 1
    Well with absolutely position elements its left/right properties are relative to its first non-statically positioned ancestor. Posting your markup might help. – Musa Oct 04 '12 at 00:28

2 Answers2

4

The definition of pageX is:

pageX is an integer value in pixels for the X coordinate of the mouse pointer, relative to the whole document, when the mouse event fired. This property takes into account any horizontal scrolling of the page.

If you put this kind of code :

    $(document.body).click(function(mouseEvent) {

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

It work perfectly.

If the div is not at the desired position, its because you DIV may have a refence point different from the body (different from the top left corner of the browser).

Indeed, absolute positionned element refer to the first reference parent. If no reference parent found, the final reference parent is body. May be you have an intermediate element which has the CSS property : position: relative. This CSS property make the element a reference for positionning and induce a shift.

MatRt
  • 3,494
  • 1
  • 19
  • 14
  • 1
    To avoid a shift due to "position: relative" of a parent element, use "position: fixed" for "#MyDiv". Warning! Only works as expected as long as there is no scrollbar! – Jack Miller Jan 31 '18 at 12:25
  • 2
    In case of scrollbar you need to subtract the current scroll position (check https://stackoverflow.com/a/2481776/2484903). – Jack Miller Jan 31 '18 at 12:33
3

This Worked for me.Try this:

<!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 the demo

Kaidul
  • 15,409
  • 15
  • 81
  • 150
  • 3
    This is not working fine if window has scroll bar. After scrolling div does not align to click point position. – Rohit Kumar Apr 25 '14 at 13:00