event.clientX and event.clientY vs event.x and event.y - javascript

When detecting mouse x and y coordinates, is it best to use event.clientX and event.clientY like this:
function show_coords(event){
var x=event.clientX;
var y=event.clientY;
alert("X coords: " + x + ", Y coords: " + y);
}
or use x and y, like this:
function show_coords(event){
var x=event.x;
var y=event.y;
alert("X coords: " + x + ", Y coords: " + y);
}
Is one method better/faster than the other? They seem to work identically to me.

I guess event.x/y are defined only in IEs. A quote from IE documentation:
"event.clientX: Retrieves the x-coordinate of the mouse cursor relative to the client area of the window, excluding window decorations or scroll bars."
"event.x: Retrieves the x-coordinate of the mouse cursor relative to the parent element."
As putvande stated, clientX maybe not cross-browser either. pageX/Y might be a safer choice.

Related

Get cursor position at frequent interval

I'm trying to get mouse cursor current position at frequent interval.
function checkMousePos(ev){
alert(true);
var x = ev.clientX,
y = ev.clientY;
alert('' + x + ' ' + y);
}
setInterval(checkMousePos, 500);
This code alerts true, but never x and y.
What am I not doing right ?
When debugging something you far better using something like console.log(myVariable) and then viewing it in the console. In your case ev not being pass by your interval and there for it's undefined. What seems like this:
var x;
var y;
document.addEventListener('mousemove', function(event){
x = event.pageX;
y = event.pageY;
})
function checkMousePos(){
console.log("Cursor at: " + x + ", " + y);
}
setInterval(checkMousePos, 500);
Although it's usually not the best solution.

Placing mouse pointer within a given diameter

I want to display an alert when the user moves his mouse pointer from coordinate X=42, Y= 10 to the coordinates X=40, Y=200.
However, since these mouse points are very small, the user might not start and end at the exact coordinates. So what i want to do is to give a range where the user could start and end when the mouse is within a certain diameter.
How can i do this ?
Is it what you're looking for?
$("body").mousemove(function(event) {
var radius = 10, yourX = 40, yourY = 10;
var xDimenion = yourX > event.pageX ? yourX - event.pageX : event.pageX - yourX;
var yDimenion = yourY > event.pageY ? yourY - event.pageY : event.pageY - yourY;
if(Math.sqrt(xDimenion * xDimenion + yDimenion * yDimenion ) < radius){
//do some stuff
}
});
I think it's ok now.
Would Client-Side Image Maps work http://www.tutorialspoint.com/html/html_image_links.htm (bottom) using an Image of a Dot and and "area shape" that is set to "circle"; that gives an exact radius (and the option to use poly) for a mouseover.

How do I get the original position of "ui.draggable" in the "drop" event?

I drag a "draggable" object to a "droppable" object. I want to know if something is already there in the position. I have already done that (without jQuery UI).
Can I do it somehow with jQuery UI?
If there is an object already present, the dragged object must revert to the original position. How can I get the original position of ui.draggable inside the "drop" event?
Thanks.
You can find answer from previous post Draggable revert if outside this div and inside of other draggables (using both invalid and valid revert options)
Demo is here http://jsfiddle.net/htWV3/1/
Look at the following, this may help
$(document).ready(function() {
var x;
var y;
$("#div1").mousedown(function(e) {
var pos = $(this).offset();
x = e.pageX - pos.left;
y = e.pageY - pos.top;
//alert(x + "," + y);
$("#drag").show().css({
top: y,
left: x
});
$("#drag").draggable();
});
$("#div1").mouseup(function(e) {
var pos = $(this).offset();
var a = e.pageX - pos.left;
var b = e.pageY - pos.top;
alert("Start-Top:" + y + "Start-Left" + x + "End-Top" + b + "End-Left" + a);
});
});​

How to constrain a text element within an square with RaphaelJS?

I'm trying to constrain a text element with custom font within a square. I'm having difficulties to let the constrainment take place.
My code looks like this for the move function:
if (this.attr("y") > offsetY || this.attr("x") > offsetX) { // keep dragging & storing original x and y
this.attr({
x : this.ox + dx,
y : this.oy + dy
});
} else {
nowX = Math.min(offsetX, this.ox + dx);
nowY = Math.min(offsetY, this.oy + dy);
nowX = Math.max(0, nowX);
nowY = Math.max(0, nowY);
this.attr({
x : nowX,
y : nowY
});
}
The constrainment never takes place. However, if I use two squares with this code, it works. What am I overlooking here?
Thanks for your answers :)
If you used the default text-anchor value of 'middle' when you called paper.text(), the x and y attrs will return the coordinates of the center of the text span -- not its upper left corner, as it would with a rect.
Rather than using the x and y attributes, you should get your coordinates via element.getBBox(), and then use the x and y from the resulting object. That should enable your existing logic to work unimpeded.

Getting mouse location in canvas [duplicate]

This question already has answers here:
How do I get the coordinates of a mouse click on a canvas element? [duplicate]
(22 answers)
Closed 3 years ago.
Is there a way to get the location mouse inside a <canvas> tag? I want the location relative to to the upper right corner of the <canvas>, not the entire page.
The accepted answer will not work every time. If you don't use relative position the attributes offsetX and offsetY can be misleading.
You should use the function: canvas.getBoundingClientRect() from the canvas API.
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y);
}, false);
Easiest way is probably to add a onmousemove event listener to the canvas element, and then you can get the coordinates relative to the canvas from the event itself.
This is trivial to accomplish if you only need to support specific browsers, but there are differences between f.ex. Opera and Firefox.
Something like this should work for those two:
function mouseMove(e)
{
var mouseX, mouseY;
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
/* do something with mouseX/mouseY */
}
Also note that you'll need CSS:
position: relative;
set to your canvas tag, in order to get the relative mouse position inside the canvas.
And the offset changes if there's a border
I'll share the most bulletproof mouse code that I have created thus far. It works on all browsers will all manner of padding, margin, border, and add-ons (like the stumbleupon top bar)
// Creates an object with x and y defined,
// set to the mouse position relative to the state's canvas
// If you wanna be super-correct this can be tricky,
// we have to worry about padding and borders
// takes an event and a reference to the canvas
function getMouse = function(e, canvas) {
var element = canvas, offsetX = 0, offsetY = 0, mx, my;
// Compute the total offset. It's possible to cache this if you want
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
// Also add the <html> offsets in case there's a position:fixed bar (like the stumbleupon bar)
// This part is not strictly necessary, it depends on your styling
offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
offsetY += stylePaddingTop + styleBorderTop + htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object with x and y defined
return {x: mx, y: my};
}
You'll notice that I use some (optional) variables that are undefined in the function. They are:
stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;
stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;
styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;
styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
// Some pages have fixed-position bars (like the stumbleupon bar) at the top or left of the page
// They will mess up mouse coordinates and this fixes that
var html = document.body.parentNode;
htmlTop = html.offsetTop;
htmlLeft = html.offsetLeft;
I'd recommend only computing those once, which is why they are not in the getMouse function.
For mouse position, I usually use jQuery since it normalizes some of the event attributes.
function getPosition(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - $(targ).offset().left;
var y = e.pageY - $(targ).offset().top;
return {"x": x, "y": y};
};
// now just make sure you use this with jQuery
// obviously you can use other events other than click
$(elm).click(function(event) {
// jQuery would normalize the event
position = getPosition(event);
//now you can use the x and y positions
alert("X: " + position.x + " Y: " + position.y);
});
This works for me in all the browsers.
EDIT:
I copied the code from one of my classes I was using, so the jQuery call to this.canvas was wrong. The updated function figures out which DOM element (targ) caused the event and then uses that element's offset to figure out the correct position.
GEE is an endlessly helpful library for smoothing out troubles with canvas, including mouse location.
Simple approach using mouse event and canvas properties:
JSFiddle demo of functionality http://jsfiddle.net/Dwqy7/5/
(Note: borders are not accounted for, resulting in off-by-one):
Add a mouse event to your canvas
canvas.addEventListener("mousemove", mouseMoved);
Adjust event.clientX and event.clientY based on:
canvas.offsetLeft
window.pageXOffset
window.pageYOffset
canvas.offsetTop
Thus:
canvasMouseX = event.clientX - (canvas.offsetLeft - window.pageXOffset);
canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
The original question asked for coordinates from the upper right (second function).
These functions will need to be within a scope where they can access the canvas element.
0,0 at upper left:
function mouseMoved(event){
var canvasMouseX = event.clientX - (canvas.offsetLeft - window.pageXOffset);
var canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
}
0,0 at upper right:
function mouseMoved(event){
var canvasMouseX = canvas.width - (event.clientX - canvas.offsetLeft)- window.pageXOffset;
var canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
}
I'd use jQuery.
$(document).ready(function() {
$("#canvas_id").bind( "mousedown", function(e){ canvasClick(e); } );
}
function canvasClick( e ){
var x = e.offsetX;
var y = e.offsetY;
}
This way your canvas can be anywhere on your page, relative or absolute.
Subtract the X and Y offsets of the canvas DOM element from the mouse position to get the local position inside the canvas.

Categories