This question already has answers here:
How to get mouse position in jQuery without mouse-events?
(7 answers)
Closed 3 years ago.
In Javascript, within the Javascript event handler for onMouseMove how do I get the mouse position in x, y coordinates relative to the top of the page?
if you can use jQuery, then this will help:
<div id="divA" style="width:100px;height:100px;clear:both;"></div>
<span></span><span></span>
<script>
$("#divA").mousemove(function(e){
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
$("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
$("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
});
</script>
here is pure javascript only example:
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else { // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
document.Show.MouseX.value = tempX;//MouseX is textbox
document.Show.MouseY.value = tempY;//MouseY is textbox
return true;
}
This is tried and works in all browsers:
function getMousePos(e) {
return {x:e.clientX,y:e.clientY};
}
Now you can use it in an event like this:
document.onmousemove=function(e) {
var mousecoords = getMousePos(e);
alert(mousecoords.x);alert(mousecoords.y);
};
NOTE: The above function will return the mouse co-ordinates relative to the viewport, which is not affected by scroll. If you want to get co-ordinates including scroll, then use the below function.
function getMousePos(e) {
return {
x: e.clientX + document.body.scrollLeft,
y: e.clientY + document.body.scrollTop
};
}
It might be a bit overkill to use d3.js just for finding mouse coordinates, but they have a very useful function called d3.mouse(*container*). Below is an example of doing what you want to do:
var coordinates = [0,0];
d3.select('html') // Selects the 'html' element
.on('mousemove', function()
{
coordinates = d3.mouse(this); // Gets the mouse coordinates with respect to
// the top of the page (because I selected
// 'html')
});
In the above case, the x-coordinate would be coordinates[0], and the y-coordinate would be coordinates[1]. This is extremely handy, because you can get the mouse coordinates with respect to any container you want to by exchanging 'html' with the tag (e.g. 'body'), class name (e.g. '.class_name'), or id (e.g. '#element_id').
Especially with mousemove events, that fire fast and furious, its good to pare down the handlers before you use them-
var whereAt= (function(){
if(window.pageXOffset!= undefined){
return function(ev){
return [ev.clientX+window.pageXOffset,
ev.clientY+window.pageYOffset];
}
}
else return function(){
var ev= window.event,
d= document.documentElement, b= document.body;
return [ev.clientX+d.scrollLeft+ b.scrollLeft,
ev.clientY+d.scrollTop+ b.scrollTop];
}
})()
document.ondblclick=function(e){alert(whereAt(e))};
Related
Using Javascript, I would like to reposition an object using a event drag.
Is tracking the distance the mouse moved the only way of getting the location of the object before drop?
In this example, there is not "drop location" as I will simply be updating the object's location based on where the user drags the mouse.
Thanks!
Cross Browser compatibility is an issue so the code is kind of funky. This code should work on any Browser.
This is based on the mouseup event.You could use the mousemove event instead.
If the event listener is added to the window, it will not work in IE8 and prior.
<!DOCTYPE html><html lang="en"><head><title>Floor Plan</title>
<style type="text/css">
#page{width:100%;padding:0;}
</style>
<body><div id="page" onmouseup="fpos(event)">
</div></body></html>
EOT;
ob_flush();
echo <<<EOT
<script type="text/javascript">//<![CDATA[
var fp = document.getElementById('fp');
var ptr = document.getElementById('point');
function fpos(e) {
var x = 0;
var y = 0;
e = e || window.event;
if (e.pageX || e.pageY){
x = e.pageX;
y = e.pageY;
}
else if (e.clientX || e.clientY) {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
var offSet = findPos(fp);
x -= offSet[0];
y -= offSet[1];
find(x,y);
}
function findPos(obj) {
var currentLeft = currentTop = 0;
if (obj.offsetParent) {
do {
currentLeft += obj.offsetLeft;
currentTop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [currentLeft,currentTop];
}}
I wrote this simple code to print a small dot on the location where I clicked with the mouse pointer:-
$(document).ready(function(){
$('#pane').click(function(e){
var pixel = $('<div />')
.addClass('pixel')
.css({
top: e.clientY,
left: e.clientX
});
$('#pane').append(pixel)
});
});
See this fiddle I created. When I click anywhere inside the rectangle, a small dot is printed in that location. But the problem is that dot is not printed where the mouse pointer's tip was. See the below image to see what I meant:-
I tried in both Firefox and Chrome.
Your code is working correctly,
Zoom your page and check,
i have changed pixel height and width for better understanding from 2px to 3px.
and drawing from e.clientX -1 and e.clientY -1 position so it looks exactly center.
You can find Fiddle
The most examples I've found don't work if there are a scrolled page... I used this algorythm in order to get the position:
var getOffsets = function($event){
var p = {};
var body = "search the document for the body element";
p.x = body.offsetLeft;
p.y = body.offsetTop;
while (body.offsetParent) {
p.x = p.x + body.offsetParent.offsetLeft;
p.y = p.y + body.offsetParent.offsetTop;
if (body == document.getElementsByTagName("body")[0]) {
break;
}
else {
body = body.offsetParent;
}
}
return p;
}
However, after that you have to consider also other elements, im my case:
var GetExactClickPosition = function($event){
var tr = $($event.target);
if ($event.target.localName != 'tr'){
tr = $($event.target).closest('tr');
}
var listDiv = $($event.target).closest('div');
var p = getOffsets($event);
var container = $('#mailingListExcludeMenuContainer');
container.css({
top: p.y - listDiv.scrollTop() - tr.height() - container.height() + $event.offsetY + "px",
left: p.x + $event.offsetX + "px"
});
container.show();
};
I have a list with scroller inside the main scroller of the page...
I used it in order to show a little menu at the position of the mouse click.
On the following page I have a popup that is supposed to show beside the image, depending on the window size the pop-up displays further/closer to the mouse. I don't understand what is wrong with the code, that makes the pop-up not display in the same proximity to the mouse?
http://www.hughgrice.com/test/
jQuery(document).mousemove(function (e) {
mouseX = e.pageX;
mouseY = e.pageY;
follow();
});
function follow(){
d = document.getElementById("thumbTT");
if(openToolTip){
d.style.display = "block";
d.style.left = mouseX+5 + "px";
d.style.top = mouseY-100 + "px";
}else{
d.style.display = "none";
}
}
http://www.hughgrice.com/test/
This should work:
var $elem = $( '#thumbTT' );
$( document ).on( 'mousemove', function ( e ) {
follow( e.pageX, e.pageY );
});
function follow ( x, y ) {
if( openToolTip ) {
$elem.css({ left: x + 5, top: y - 100 }).show();
} else {
$elem.hide();
}
}
I'm assuming that the #thumbTT element is static, so I'm caching the reference to it beforehand.
As your wrapper DIV is relative positioned that's why it is not positioned correctly. Either you have to remove the position:relative from your wrapper div or you have to write your mousemove function like
jQuery(document).mousemove(function (e) {
var offset = jQuery(this).css('offset');
mouseX = offset.left;
mouseY = offset.top;
follow();
});
maybe you have to adjust your code
I'm trying to have a selection wheel appear when the user holds down the Shift key.
The wheel should be centred on the mouse's position.
However when I test this, pageX and clientX are both undefined on the event object.
Is it possible to get the mouse coordinates on a keyboard event?
No, simply track mousemove events and continuously save the current position in case you get a keyboard event.
Cache mouse position in a global variable in every mousemove event and use it when a key event fires:
var mousePosition = {x:0, y:0};
$(document).bind('mousemove',function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
});
$(document).bind('keyup', function(keyUpEvent){
$('body').append($('<p/>').text('x:' + mousePosition.x + ' * y: ' + mousePosition.y));
});
JSBIN: http://jsbin.com/uxecuj/4
JavaScript without jQuery:
var mousePosition = {x:0, y:0};
document.addEventListener('mousemove', function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
}, false);
document.addEventListener('keyup', function(keyUpEvent){
var divLog = document.querySelector('#log'),
log = 'x:' + mousePosition.x + ' * y: ' + mousePosition.y,
p = document.createElement('p').innerHTM = log;
divLog.appendChild(p);
}, false);
Here's the POJS equivalent of other answers that is cross browser back to IE 6 (and probably IE 5 but I don't have it to test any more). No global variables even:
function addEvent(el, evt, fn) {
if (el.addEventListener) {
el.addEventListener(evt, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + evt, fn);
}
}
(function () {
var x, y;
window.onload = function() {
addEvent(document.body, 'mousemove', function(e) {
// Support IE event model
e = e || window.event;
x = e.pageX || e.clientX;
y = e.pageY || e.clientY;
});
// Show coords, assume element with id "d0" exists
addEvent(document.body, 'keypress', function() {
document.getElementById('d0').innerHTML = x + ',' + y;
});
}
}());
But there are bigger issues. Key events are only dispatched if an element that can receive keyboard input is focused (input, textarea, and so on). Also, if the user scrolls the screen without moving the mouse, the coordinates will probably be wrong.
An alternative solution is to use CSS to replace the cursor with a custom animation.
If you're using jQuery, you can do the following (assuming you have an image with id="wheelImage" and whose position is set to absolute), write the following inside your keydown event. Here we use the global properties pageX and pageY that are passed to any handler. You can also use jQuery's shiftKey property to check if the shift key has been pressed.
$().keydown(function(e) {
if (e.shiftKey) {
e.preventDefault();
$('#wheelImage').css('left',e.pageX ).css('top', e.pageY);
}
});
Cache the mouse position.
var x = 0, y = 0;
document.addEventListener('mousemove', function(e){
x = e.pageX
y = e.pageY;
}, false);
document.addEventListener('keyup', function(e){
console.log(x + ' ' + y);
}, false);
Or with JS Ninja Library.
var x = 0, y = 0;
$(document).mousemove(function(e){
x = e.pageX
y = e.pageY;
});
$(document).keypressed(function() {
console.log(x + ' ' + y);
});
I have the following event handler for my html element
jQuery("#seek-bar").click(function(e){
var x = e.pageX - e.target.offsetLeft;
alert(x);
});
I need to find the position of the mouse on the #seek-bar at the time of clicking. I would have thought the above code should work, but it gives incorrect result
Are you trying to get the position of mouse pointer relative to element ( or ) simply the mouse pointer location
Try this Demo : http://jsfiddle.net/AMsK9/
Edit :
1) event.pageX, event.pageY gives you the mouse position relative document !
Ref : http://api.jquery.com/event.pageX/
http://api.jquery.com/event.pageY/
2) offset() : It gives the offset position of an element
Ref : http://api.jquery.com/offset/
3) position() : It gives you the relative Position of an element i.e.,
consider an element is embedded inside another element
example :
<div id="imParent">
<div id="imchild" />
</div>
Ref : http://api.jquery.com/position/
HTML
<body>
<div id="A" style="left:100px;"> Default <br /> mouse<br/>position </div>
<div id="B" style="left:300px;"> offset() <br /> mouse<br/>position </div>
<div id="C" style="left:500px;"> position() <br /> mouse<br/>position </div>
</body>
JavaScript
$(document).ready(function (e) {
$('#A').click(function (e) { //Default mouse Position
alert(e.pageX + ' , ' + e.pageY);
});
$('#B').click(function (e) { //Offset mouse Position
var posX = $(this).offset().left,
posY = $(this).offset().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
$('#C').click(function (e) { //Relative ( to its parent) mouse position
var posX = $(this).position().left,
posY = $(this).position().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
});
$('#something').click(function (e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
console.log(xPos, yPos);
});
Try this:
jQuery(document).ready(function(){
$("#special").click(function(e){
$('#status2').html(e.pageX +', '+ e.pageY);
});
})
Here you can find more info with DEMO
In percentage :
$('.your-class').click(function (e){
var $this = $(this); // or use $(e.target) in some cases;
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var posX = offset.left;
var posY = offset.top;
var x = e.pageX-posX;
x = parseInt(x/width*100,10);
x = x<0?0:x;
x = x>100?100:x;
var y = e.pageY-posY;
y = parseInt(y/height*100,10);
y = y<0?0:y;
y = y>100?100:y;
console.log(x+'% '+y+'%');
});
If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.
The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
$("#seek-bar").click(function(event) {
var x = event.offsetX
alert(x);
});
see here enter link description here
html
<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>
css
#myPosition{
background-color:red;
height:200px;
width:200px;
}
jquery
$(document).ready(function(){
$("#myPosition").click(function(e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
alert("X position: " + xPos + ", Y position: " + yPos);
});
});