Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

e.pageX and e.pageY not working correctly?

Tags:

jquery

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});
like image 923
Mike Avatar asked Oct 04 '12 00:10

Mike


People also ask

What is pageX and pageY?

The pageX property returns the horizontal coordinate (according to the document) of the mouse pointer when a mouse event was triggered. The document is the web page. Tip: To get the vertical coordinate (according to the document) of the mouse pointer, use the pageY property. Note: This property is read-only.

What is event pageY?

The event. pageY property returns the position of the mouse pointer, relative to the top edge of the document. Tip: This event property is often used together with the event. pageX property.


1 Answers

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.

like image 125
MatRt Avatar answered Sep 30 '22 09:09

MatRt