How can I get the coordinates of my mouse? [duplicate] - javascript

This question already has answers here:
Javascript - Track mouse position
(18 answers)
Closed 7 years ago.
I'm writing a script that will repeatedly write my mouse coordinates to an element as I navigate with it. But I'm not sure how to detect information from the mouse. Some one wanna point me in the right direction?
document.getElementById("coords").innerHTML = crdX + ", " + crdY
http://jsfiddle.net/7pj9gpvn/
EDIT: My question is not a duplicate of the proposed question because the proposed question is concerned with the loop aspect of the same problem, whereas mine is concerned with the 'event handling' aspect. I did read and attempt to ascertain the information I needed from that question, but as I am a beginner, I found their code difficult to read.

Try This works on all browser
http://jsfiddle.net/7hxtLqd4/
<html>
<body>
<form name="mShow">
<input type="text" name="MX" value="0" size="4"> X
<br>
<input type="text" name="MY" value="0" size="4"> Y
<br>
</form>
<script language="JavaScript1.2">
var IE = document.all ? true : false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouse;
var tempX = 0
var tempY = 0
function getMouse(e) {
if (IE) {
tempX = event.clientX + document.body.scrollLeft
tempY = event.clientY + document.body.scrollTop
} else {
tempX = e.pageX
tempY = e.pageY
}
if (tempX < 0) {
tempX = 0
}
if (tempY < 0) {
tempY = 0
}
// ADD TEMP VALUE FOR FIELDS
document.mShow.MX.value = tempX
document.mShow.MY.value = tempY
return true
}
</script>
</body>
</html>

You need to attach a MouseEvent and the event object passed to the handler will give you the coordinates. Attach it to the document if you want to track the movement everywhere. clientX and clientY properties give you local coordinates while screenX and screenY give you global coordinates.
Fiddle: http://jsfiddle.net/AtheistP3ace/7pj9gpvn/4/
HTML:
<p id="coords"></p>
<p id="coords2"></p>
JS:
document.addEventListener('mousemove',
function (event) {
var para = document.getElementById('coords');
para.textContent = event.clientX + ", " + event.clientY;
var para2 = document.getElementById('coords2');
para2.textContent = event.screenX + ", " + event.screenY;
}
);
Feel free to read up on it yourself too: https://developer.mozilla.org/en-US/docs/Web/Events/mousemove

Related

Mouse position not working for FireFox

I am stuck in an issue. I have to fetch mouse positions on firefox browser. However it is not working may be I am doing any mistake in code. So far I have done is given below.
Javascript Code :
function MousePos(event){
if ($.browser.mozilla == true){
if(typeof event.offsetX === "undefined" || typeof event.offsetY === "undefined"{
var targetOffset = $(event.target).offset();
event.offsetX = event.pageX - targetOffset.left;
event.offsetY = event.pageY - targetOffset.top;
alert(event.offsetX + " " + event.offsetY);
}
}
}
HTML Code :
<div class="paymentTracker" onmouseover="MousePos();">
</div>
The function is working if I show an alert box only but this code having issue. I want mouse positions only on Firefox browser.
Thanks in advance.
try this : I think its not working because its not taking onmouseover function you have defined in html.
$( ".paymentTracker" ).mouseover(function(event) {
var x = event.clientX;
var y = event.clientY;
var coords = "X coords: " + x + ", Y coords: " + y;
alert(coords);
});
<div class="paymentTracker"></div>
<style>
.paymentTracker {width:300px; height:300px;border:1px solid;}
</style>
heres the fiddle : https://jsfiddle.net/0yptrjdw/
with your code
$( ".paymentTracker" ).mouseover(function(event) {
var targetOffset = $(event.target).offset();
event.offsetX = event.pageX - targetOffset.left;
event.offsetY = event.pageY - targetOffset.top;
alert(event.offsetX + " " + event.offsetY);
});

how to get mouse coordinate after transform

How do I get the x and y pixel value of the mouse click on the image after a canvas translate & scale? What's the needed calculation from the event x and y?
I am using panning & zooming code from this answer:
var zoom = function(clicks) {
var pt = ctx.transformedPoint(lastX,lastY);
ctx.translate(pt.x,pt.y);
var factor = Math.pow(scaleFactor,clicks);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);
redraw();
}
var handleScroll = function(evt) {
var delta = evt.wheelDelta ? evt.wheelDelta/40 : evt.detail ? -evt.detail : 0;
if (delta) zoom(delta);
return evt.preventDefault() && false;
};
Example website
If you're just trying to get the mouse X and Y position after a click, then you should attach a function to the mousedown event in Javascript. This is called event binding. In short, while in the DOM you can bind events to elements within the page. Here's an example I made which shows an event bound to the #box element.
document.getElementById("box").onmousedown = function() {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
alert("Mouse x: " + posx + "\nMouse y: " + posy);
};​
This code finds an element with an ID of box and tells the code in the function to run every time after the mouse is depressed. In this example we also fall back for older system to ensure that it works cross-platform and cross-browser. If you wanted to bind this event to the whole webpage rather than just an element then you can replace document.getElementById("box") with window.
This however does not compute the relative position within a DOM element. There's multiple ways to do that which I won't go into detail on here, but I'll include a few methods below. Best of luck!
RESOURCES
More on handling mouseclicks in Javascript
Relative position of mouse clicks within an element
jQuery solution for the previous link

Image showing different coordinates on different browsers

I am plotting an image of fixed width and height. I am allowing the user to click on the image - and storing the location (x-y coordinates) where the image was clicked. Here is a sample code:
<script language="JavaScript" type="text/JavaScript">
var posx; var posy;
function showP(e) {
// captures the mouse position
posx = 0; posy = 0;
if (!e) { var e = window.event; }
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX;
posy = e.clientY;
}
alert('X mouse is: ' + posx + ' Y mouse is: ' + posy );
}
</script>
I am noticing that for a fixed point on the image, I am getting different X and Y coordinates on different browsers.
Can anyone tell why this is the case.
Thanks
you can check all data that you get in your event
var a = "";
for (var key in e){
if( typeof e[key]!='function' && typeof e[key] !='object' )
a += key+'='+ e[key]+'\n'
}
alert(a)
this constraction helps you compare margin and padding in browsers
var padding = parseInt($("#imgId").css("padding-top"));
I think you need investigate you code and styles, maybe you have some conflict with padding and margins that influences on you result.
Hope this way helps you.

mouse coordinates in javascript?

I created a small function to get mouse coordinates in div but somehow it is not working. I checked my function thoroughly but I didn't find the bug.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script type="text/javascript">
function SetValues()
{
var s = "X:" + window.event.clientX + " Y:" + window.event.clientY ;
document.getElementById('divCoord').innerHTML = s;
}
</script>
</head>
<body onmousemove=SetValues()>
<div id="divCoord"></div>
</body>
</html>
The window.event property is only present in Internet Explorer, and only in some versions I think. In fact, the entire operation you are trying to do requires some fairly advanced cross-browser coding.
I suggest you consider using a JavaScript framework that normalizes events, such as jQuery.
Using jQuery, and this will work in all browsers:
$(document).mousemove(function(e) {
$('#divCoord').html('X:' + e.pageX + ' Y:' + e.pageY);
});
Try this code :
JS
document.onmousemove = getMouseXY;
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;
}
HTML
X <input type="text" name="MouseX" value="0" size="4"><br>
Y <input type="text" name="MouseY" value="0" size="4"><br>
Source
window.event.clientX & window.event.clientY
try:
$(document).ready(function(e) {
$('body').live('mousemove', function(e) {
alert('x: ' + window.event.clientX + ', y: ' + window.event.clientY);
})
});

HTML5 Canvas and Firefox 4 - Getting click coordinates

I've been working on a bunch of HTML5 Video and Canvas demos. Til now I focused on Chrome, but now I'm trying to optimize them for Firefox and Safari as well.
The one I'm working on right now draws a video in Canvas and moves the video to mouseclick positions. What I have so far works in Chrome and Safari, but not in Firefox. I haven't been able to find much info on these topics (click events, coordinates, firefox-specific etc). I copied the code from here:
How do I get the coordinates of a mouse click on a canvas element?
http://answers.oreilly.com/topic/1929-how-to-use-the-canvas-and-draw-elements-in-html5/
because they gave me the impression it should work in all browsers, but Firefox still refuses. All it does is display the video, it doesn't react to mouse clicks.
This is my code (not including the definition of variables):
function activateVideo(){
setTarget();
videoElement.play();
animate();
}
function setTarget(){
targetX=xCoord;
targetY=yCoord
moverX=(targetX-currentX)/100;
moverY=(targetY-currentY)/100;
}
canvasElement.addEventListener('click', function(){
/*xCoord = event.clientX - canvasElement.offsetLeft;
yCoord = event.clientY - canvasElement.offsetTop;
txtCount.value = xCoord + " + " + yCoord;*/
if (event.pageX || event.pageY) {
xCoord = event.pageX;
yCoord = event.pageY;
} else {
xCoord = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
yCoord = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
xCoord -= canvasElement.offsetLeft;
yCoord -= canvasElement.offsetTop;
setTarget();
},false);
function animate(){
currentX += moverX;
currentY += moverY;
if(dist(currentX,targetX,currentY,targetY)<1) {
moverX=0;
moverY=0;
}
drawVideo(videoElement,context,320,256);
timer = setTimeout(animate,20);
}
function dist(x1,x2,y1,y2){
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
function drawVideo(videoElement,context,w,h) {
context.clearRect(0,0,1000,600);
context.drawImage(videoElement,currentX,currentY,w,h);
}
playCanvas.addEventListener('click', activateVideo, false);
So obviously I'm a bit lost, if anybody could point me in the right direction, I would appreciate it.
I have a working version of this that uses jquery, which is likely the most cross-browser way of doing it. It's not that bad. Here's my fiddle http://jsfiddle.net/jaredwilli/D3PWN/
Code
var canvas = $('canvas');
canvas.mousemove(function(e){
var pageCrds = '('+ e.pageX +', '+ e.pageY +')',
clientCrds = '('+ e.clientX +', '+ e.clientY +')';
$('span:first').text('(e.pageX, e.pageY) - '+ pageCrds);
$('span:last').text('(e.clientX, e.clientY) - '+ clientCrds);
});
var arr = [];
canvas.click(function(e) {
arr.unshift($('span.first').text());
console.log(arr);
});
Hope this helps you out some. :)
You need to pass the event object to the handler for FF (IE works becuse event is available via window.event)
canvasElement.addEventListener('click', function(event){
event = event || window.event;
...

Categories

Resources