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});
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With