This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery get mouse position within an element
I have a page and inside that page I have a div.
If the user clicks inside that div it'll store the X/Y co-ordinates of where they clicked inside that div.
E.g. if I clicked in the top left corner of the div (no matter where the div was placed on the page) it'd return approximately 0, 0.
Is this even possible? and if so, could you tell me how - or even point me in the right direction?
Use pageX property of the event to get the x coordinate relative to the page and pageY to get the y coordinate, then substract the element's coordinates to get the position relative to the element.
$( '#target' ).on( 'click', function( e ) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
});
Demo: http://jsfiddle.net/WhrFt/
Official tutorial on jquery.com: http://docs.jquery.com/Tutorials:Mouse_Position
Related
I have built a javascript application for dragging and dropping divs from one place to another in the same page. I have made the dragging part. I have the co-ordinates of the div(s) where I must drop the div but I am stuck at the part where I should introduce conditions for matching the divs at target zone. Basically the divs can be dropped above any of the divs but they must drop exactly above the target div if on onmouseup event I am anywhere close to that target div. I am thinking of assigning the top and left attribute of my dragged(onmousdown) div to the target div but I may be wrong.. Please guide my through this part.
Here is the part where I need help:
function mouseUp(e)
{
e = e || window.event;
var mousePos = mouseCoords(e);
var itemPosition = getPosition(id);
//console.log("This is at: "+itemPosition);
//console.log(mousePos);
console.log(getPosition(id));
for(var i=0;i<destination.length;i++)
{
var curTarget = destination[i];
var targPos = getPosition(curTarget);
var targWidth = parseInt(curTarget.offsetWidth);
var targHeight = parseInt(curTarget.offsetHeight);
var temp = document.elementFromPoint(event.clientX, event.clientY);
}
id = null;
}
Here is the link to my code: jsfiddle The javascript part must be written inside of html to make it work properly
The question title is misleading, what you really seem to be having trouble with is finding the coordinates of the target divs. You're grabbing mouse coordinates just fine using clientX and clientY though you likely want to be using the pageX and pageY coordinates as they are relative to the rendered page and not the viewport (ie. window the user is looking at). 0,0 using the client coordinates will change as the user scrolls whereas the page coordinates will reference a particular spot on the webpage.
As for finding your drop divs you can use the method getClientBoundingRect on the element and use the top, right, bottom, and left properties on the returned object to determine if the pageX and pageY coordinates of the mouse are inside (or close to inside) the element.
Maybe there's a better way, but this is how I would do it.
function mouseUp(e){
var targets = document.getElementsByClassName("drop_here");
for(var i=0;i<targets.length;i++){
var bounds = targets[i].getClientBoundingRect();
var lenience = 5;
if(e.pageX < bounds.right + lenience &&
e.pageX > bounds.left - lenience &&
e.pageY < bounds.top - lenience &&
e.pageY > bounds.bottom + lenience){
//do my work here
}
}
}
I wish to retrieve the exact X/Y coordinates where the user has pressed on the screen. The coordinates must be the same no matter what level of zoom or scroll is applied. I am using event.clientX and event.clientY to retrieve these coordinates and this behaves as expected. The code is basically as follows:
$("#canvas").touchstart(function(e){
e.preventDefault();
var Y_LIMIT = 100
if(e.clientY <= Y_LIMIT){
... do stuff
}
});
A textarea is present on the screen with a submit button to allow the user to enter text. The issue is after the tablet focuses in on the textarea and the user enters text the clientX and clientY coordinates permanently change. I wish for the values to stay the same regardless of this operation.
Is there any way to keep clientX and clientY consistent even after entering text into a textarea or input box ?
Despite the fact that there is still a question left about how clientX & clientY have changed(did they descrease or increase their values?)
If they descreased their values you could give this a try to take the absolute position of a parent HTML element(DIV?) in which your textarea is located into consideration:
Check out this answer that answers about how to get absolute position of a HTML element:
// get absolut position of an HTML element
function cumulativeOffset (element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
// event handler callback function to retrieve client position
function funcToGetClientCoords(evt){
var area = document.getElementById("parentDIVId");
var absoluteViewportPos = cumulativeOffset(area);
return {
x: evt.clientX + absoluteViewportPos.left,
y: evt.clientY + absoluteViewportPos.top
};
}
I did not prove this but it sounds to me as if clientX & clientY coords changed according to your relative screenview position and when you click onto a textarea you automatically zoom into this textarea and so clientX and clientY coords might be descreased.
Another try could be to remember the absolute position of your parent DIV at the beginning and when interacting with your textarea add this position to clientX/clientY positions.
Hope this helps.
I am creating a tooltip and am having some problems with positioning it.
The tooltip is set to position: absolute, and I have a handler for mouse events that modifies it's top and left CSS depending on the pageX and pageY.
Now, I know I can just set the top to pageY and left to pageX. That will make the tooltip pop up to the bottom-right. I'm trying to orient it where it pops up on the top-right when there is room, but if it would be out of the viewport on the Y-axis, drop to the bottom-right position again.
At the moment, I'm stuck trying to get the tooltip to show to the top-right of the mouse. I don't even know where to begin detecting if it would be in the viewport. Can anyone point me in the right direction?
$('p').on('mouseenter', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
$(tt).appendTo('body');
}).on('mousemove', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
}).on('mouseleave', function(e) {
$(tt).detach();
});
Example on JSFiddle
There are many different ways to handle tooltips, especially when using jQuery. This method probably would not have been my first choice. However, the following changes should work how you intended.
var tt = document.createElement('div');
tt.id = "tt";
$('p').on('mouseenter', function(e) {
var curPos = $( this ).offset().top - $( window ).scrollTop();
var inView = (curPos < 250) ? 0 : 250;
$(tt).css('top', e.pageY - inView);
$(tt).css('left', e.pageX);
$(tt).append($( this ).attr("data-myId"));
$(tt).appendTo('body');
}).on('mousemove', function(e) {
$(tt).css('top', e.pageY - $(tt).css('height'));
$(tt).css('left', e.pageX);
}).on('mouseleave', function(e) {
$(tt).empty($( this ).attr("data-myId"));
$(tt).detach();
});
Full changes in JSFiddle.
I am taking advantage of jQuery's offset() and scrollTop() methods to estimate the position of the current element within the viewable area of the document.
According to jQuery's API documentation, the .offset() method
allows us to retrieve the current position of an element relative to
the document. The documentation also states that the vertical
scroll position (.scrollTop()) is the same as the number of pixels that are hidden
from view above the scrollable area.
We use both of these methods to our advantage and subtract the number of pixels above the scrollable area from the current position of the element relative to the document. One important thing to note is that the offset method returns an object with the properties top and left.
var curPos = $( this ).offset().top - $( window ).scrollTop();
Since you had the #tt id set to a static 250px height, we can check if the current element position relative to the viewable portion of the window is less than 250. If it is, then we subtract nothing and let the tool tip sit below the mouse position. If it is greater than 250 then we subtract 250px and the tool tip will be above the current mouse position.
I am not sure how you were intending to pull in the content for the tool tips, but I also added $(tt).append($( this ).attr("data-myId")); to use the data-myId value as the tool tip content and $(tt).empty($( this ).attr("data-myId")); to clear it on mouseleave. I hope this helps!
is there an easy way to find where user clicked inside an image (div, ...), relative to top-left corner of the element? (using js/jquery)
Basic event.pageX/event.pageY does not take into account scrolling and element position. Combining Document.getScrollTop() and element.getAbsoluteTop ( Mouse click location on an image ) does not look nice at all (may not even work on all browsers as far as I know).
Is there a simpler way to this?
This seems simple enough:
$('#yourImg').click(function(e){
var x = e.pageX - e.target.offsetLeft,
y = e.pageY - e.target.offsetTop;
});
See demo →
I need know what elements are in current mouse position and I'm using jQuery.
If I understood you correctly you need to find out the element over the mouse is currently on. If this is correct you can use
document.elementFromPoint ( x, y );
document.elementFromPoint
Returns the element from the document
whose elementFromPoint method is being
called which is the topmost element
which lies under the given point. The
point is specified via coordinates, in
CSS pixels, relative to the
upper-left-most point in the window or
frame containing the document.
$(document).ready(function(){
$(this).mousemove(function(e){
var elem = document.elementFromPoint ( e.pageX , e.pageY );
alert ( elem.id );
});
})