javascript onmousemove get relative coordinates - javascript

function aim() {
var mousex = ?
}
<div class="gameArea" onmousemove="aim();"> </div>
I can't find how to get the mouse coordinates for an onmousemove event in javascript.

var guide = null;
function aim(event) {
if(window.event)
event = window.event; //grrr IE
var mousex = event.clientX - guide.offsetLeft;
alert('mouse x' + mousex)
}
function init() {
guide = document.getElementById("guide")
guide.onmousemove = aim;
}
<body onload="init();">
This appears to work on both browsers. I cant do onmousemove="aim();" in html because it doesn't pass the mousemove event object.

The above example using guide.offsetLeft only works if the enclosing element is at (0,0). If not, you can use guide.getBoundingClientRect().left (and similar for vertical coord)

Take a lot at the following script. I believe it should be exactly what you're looking for.
Capture Mouse Position

Related

How do get I the clickable point from a html element?

how do I get the x,y coordinates from a HTML element relative to screen?
I'm using x,y from getBoundingClientRect() as below, but as you can see in the blow image, if I use move the cursor to this x,y position, the curson is in the middle between 0 and + buttons not the 5 button, which is the target button.
What am I missing?
JS code:
var e = document.querySelector('input[id=five]');"
var r = e.getBoundingClientRect();
var x = r.x;
var y = r.y;
MoveMouseTo(x,y); // imaginary call, the real cursor move is done by C# but I can share the code, as needed.
Image:
NOTE: if this aditional info may help, it's a C# application with embedded browser.
const getCoords = (e) => {
var x = e.clientX
var y = e.clientY
var xx = e.screenX
var yy = e.screenY
console.log(x, y, "client")
console.log(xx, yy, "screen")
}
You're going to want to assign this function to a onmousemove event to the outermost div containing the UI for your calculator. This should at least show you the difference between a screen X,Y and a client X,Y
https://www.w3schools.com/code/tryit.asp?filename=FVXZOK1SPTR0
You can try to add an event listener on your element and use the event to retrieve the coordinates of the mouse.
const $element = document.querySelector('input[id=five]');
$element.addEventListener('mousemove', handleMouseMove);
function handleMouseMove (event) {
console.log('Offset from the screen coordinates', event.screenX, event.screenY);
// The client refers to the element you are bound to;
console.log('Offset from the client coordinates', event.clientX, event.clientY);
};

How to correctly get mouse coordinates with JavaScript without JQuery?

I am aware of the fact that variations of that question were asked many times before. Looking through Google output I found pages with examples like that:
function point_it(event) {
pos_x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("pointer_div").offsetLeft;
pos_y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("pointer_div").offsetTop;
document.pointform.form_x.value = pos_x;
document.pointform.form_y.value = pos_y;
}
The code works, but when I look at
MouseEvent.offsetX it says "This is an experimental technology...".
So my question is, is it save to use the above construction or not? Is it better to learn how to use JQuery?
Please try this
function getClickPosition(e) {
var xPosition = e.clientX;
var yPosition = e.clientY;
}
Call this function on "onClick" event. You can get the coordinates.
Output the coordinates of the mouse pointer when the mouse button is clicked on an element.

.setCapture and .releaseCapture in Chrome

I have an HTML5 canvas based Javascript component that needs to capture and release mouse events. In the control the user clicks an area inside it and drags to affect a change. On PC I would like the user to be able to continue dragging outside of the browser and for the canvas to receive the mouse up event if the button is released outside of the window.
However, according to my reading setCapture and releaseCapture aren't supported on Chrome.
Is there a workaround?
An article written in 2009 details how you can implement cross-browser dragging which will continue to fire mousemove events even if the user's cursor leaves the window.
http://news.qooxdoo.org/mouse-capturing
Here's the essential code from the article:
function draggable(element) {
var dragging = null;
addListener(element, "mousedown", function(e) {
var e = window.event || e;
dragging = {
mouseX: e.clientX,
mouseY: e.clientY,
startX: parseInt(element.style.left),
startY: parseInt(element.style.top)
};
if (element.setCapture) element.setCapture();
});
addListener(element, "losecapture", function() {
dragging = null;
});
addListener(document, "mouseup", function() {
dragging = null;
}, true);
var dragTarget = element.setCapture ? element : document;
addListener(dragTarget, "mousemove", function(e) {
if (!dragging) return;
var e = window.event || e;
var top = dragging.startY + (e.clientY - dragging.mouseY);
var left = dragging.startX + (e.clientX - dragging.mouseX);
element.style.top = (Math.max(0, top)) + "px";
element.style.left = (Math.max(0, left)) + "px";
}, true);
};
draggable(document.getElementById("drag"));
The article contains a pretty good explanation of what's going on, but there are a few gaps where knowledge is assumed. Basically (I think), in Chrome and Safari, if you handle mousemove on the document then, if the user clicks down and holds the mouse, the document will continue receiving mousemove events even if the cursor leaves the window. These events will not propagate to child nodes of the document, so you have to handle it at the document level.
Chrome supports setPointerCapture, which is part of the W3C Pointer events recommendation. Thus an alternative would be to use pointer events and these methods.
You might want to use the jquery Pointer Events Polyfill to support other browsers.

custom event for mouse coordinates

I'm creating iFrame and in that iFrame script I need to catch mouse coordinates after creation (in very start). I was hoping that it's possible with custom event.
I tried
var myEvent = new Event('mouseC');
document.addEventListener('mouseC', function(e){
console.log('my event is working');
console.log('mouse x is '+e.pageX);
console.log('mouse y is '+e.pageY);
});
document.dispatchEvent(myEvent);
console is displaying 'my event is working', but mouse coordinates are undefined.
I tried wrapping it in window.onload, and I also tried screenX and clientX... always undefined
How can I catch mouse coordinates in newly created iFrame imedietly after creation?
...btw, mousemove event is working and writing coordinates when mouse is moved over new iFrame.
Could I somehow move mouse for just 1px to trigger that event?
iframElement = document.getElementBy...("...");
document.addEventListener("click", function(evt,iframElement){
var x = evt.pageX - iframElement.offset.left;
var y = evt.pageY - iframElement.offset.top;
console.log(x+" , "+y);
});
it might work
var value =parent.frames[FRAME_NAME].frameElement.offsetParent;
var x = 0, y = 0;
while (value)
{
x += value .offsetLeft;
y += value .offsetTop;
value = value .offsetParent;
//console x anf y...
}
console x and y you can get co ordinates of mouse inside iframe.

Getting mouse position in major internet browsers with javascript

I read this article regarding creating popup notes with javascript and css
The problem is that this one works only in IE since window.event is undefined in Firefox.
// assigns X,Y mouse coordinates to note element
note.style.left=event.clientX;
note.style.top=event.clientY;
So could you point me a fully working example? Or at least, how could i modify the javascript code to make it work in both internet browsers?
There are more than two browsers, but the following should work in most of them (adapted from the function on the page you linked to):
showNote = function(evt) {
evt = evt || window.event;
// gets note1 element
var note1=document.getElementById('note1');
// assigns X,Y mouse coordinates to 'note1' element
note1.style.left=evt.clientX;
note1.style.top=evt.clientY;
// makes note1 element visible
note1.style.visibility='visible';
};
The problem is that not all browsers have an event property of window and instead use an event object implicitly passed in as a parameter to an event handler function such as showNote. The evt = evt || window.event; line assigns window.event to the evt variable if no event parameter was passed into the function (which is what happens in Internet Explorer).
You can separate the two branches when you define the method.
It takes more characters than bundling them together,
but you do not have to check for support on every every call.
//
window.whereAt= (function(){
var fun;
if(typeof pageXOffset== 'number'){
fun= function(e){
var pX, pY, sX, sY;
pX= e.clientX || 0;
pY= e.clientY || 0;
sX= window.pageXOffset;
sY= window.pageYOffset;
return [(pX+sX), (pY+sY)];
}
}
else{
fun= function(e){
e= (e && e.clientX)? e: window.event;
var pX, pY, sX, sY;
pX= (e.clientX);
pY= (e.clientY);
var d= document.documentElement;
var b= document.body;
sX= Math.max(d.scrollLeft, b.scrollLeft);
sY= Math.max(d.scrollTop, b.scrollTop);
var pwot= [(pX+sX), (pY+sY)];
return pwot;
}
}
return fun;
})()
//test case
document.ondblclick= function(ev){
alert(whereAt(ev))
};
I finally found a solution, but using canvas.addEventListener instead of onclick funion bind in attributes of canvas. And it works in IE, FF, Chrome.
canvas.addEventListener('mousedown', ev_canvas, false);
function ev_mousedown(ev){
var posx=0;posy=0;
if (e.offsetX > 0) { // IE, Chrome
posx = e.offsetX;
posy = e.offsetY;
} else{ // Firefox
posx = e.layerX;
posy = e.layerY;
}
} // This also works correctly while zoom!=100%
<div style="position: relative;">
<canvas id="canvas" width="600" height="600" onClick="newClick()" style="position: relative;"></canvas>
</div>
See reference: http://dev.opera.com/articles/view/html5-canvas-painting/
The following codes doesn't work in Firefox.
showNote = function(evt) {
evt = evt || window.event;
// gets note1 element
var note1=document.getElementById('note1');
// assigns X,Y mouse coordinates to 'note1' element
note1.style.left=evt.clientX;
note1.style.top=evt.clientY;
// makes note1 element visible
note1.style.visibility='visible'
}
I have google for many solutions and referenced the relatively official site for browers differs: http://www.quirksmode.org/dom/w3c_cssom.html#mousepos
But still have not found a solution in Firefox 20.
window.event has no definition in FF. But works well in IE and Chrome.
I wonder have I misunderstood something in this point?

Categories

Resources