Javascript: Get X, Y Coordinates of Click in Image [duplicate] - javascript

This question already has answers here:
Find mouse position relative to element
(29 answers)
Closed 4 years ago.
here's my latest problem.
I'm trying to get the X and Y coordinates of where a user clicks inside an image. Regardless of where it's positioned in the user's window, the zoom, the scroll position, the size of window, what the user had for breakfast, etc., the X,Y coordinates have to take into account only what position the user clicks in the image but not include the position of the image in the screen, i.e. the upper left point in the image is 0,0. (Hope I'm explaining this clearly.)
The reason I say this is because, in my current JavaScript function, I'm getting the X,Y coordinates of something, but I'm not sure exactly what. I think it's the position of where the user clicks in the overall window, but not in the image. This means that the X,Y coordinates change if the position of the image is different, if the user has scrolled, if I move the image somewhere else in the page, etc. Here's my current HTML code:
<img id="hotspot_image" name="hotspot_image" style="width: 50%" src="misc/pages/hotspotimage.jpg" alt="Hotspot image" onclick="clickHotspotImage(event);"/>
And here's my Javascript function:
function clickHotspotImage(event) {
var xOffset = document.getElementById('hotspot_image').offsetLeft;
var xCoordinate = event.clientX;
var yOffset = document.getElementById('hotspot_image').offsetTop;
var yCoordinate = event.clientY;
var hotspotlist = document.getElementById('hotspot_list').value;
document.getElementById('hotspot_list').value = document.getElementById('hotspot_list').value + '\n' + xCoordinate + ',' + yCoordinate;
}
The last few lines of code in there take that X,Y coordinate pair and add it to the end of a list contained in a <textarea> tag called hotspot_list. Does anyone know if I'm on the right track or can point me in the right direction, or knows what missing piece I need to get that true X,Y coordinate? Thanks!

You should use offsetX and offsetY from you event object to get the mouse coordinates relative to the element that fires the event. clientX and clientY will return mouse coordinates relative to the window, as you have noted.
Event object properties
This should do the trick
function clickHotspotImage(event) {
var xCoordinate = event.offsetX;
var yCoordinate = event.offsetY;
var hotspotlist = document.getElementById('hotspot_list').value;
document.getElementById('hotspot_list').value = document.getElementById('hotspot_list').value + '\n' + xCoordinate + ',' + yCoordinate;
}

Related

Setting the correct transform-orign x and y value for a rotated element

In JavaScript/jQuery, if we wanted to rotate an element around an origin point defined by the click point, you could do this:
var angle = 0;
$('#myElement').on('click', function(event) {
const ELEMENT_X = event.pageX - $(this).offset().left;
const ELEMENT_Y = event.pageY - $(this).offset().top;
angle +=10;
$(this).css('transform-origin', ELEMENT_X + 'px ' + ELEMENT_Y + 'px');
$(this).css('transform', 'rotate(' + angle + 'deg)');
});
So it works as planned on the first click because the element is not in a rotated state. After the first rotation, the ELEMENT_X AND ELEMENT_Y are not set correctly obviously, which causes the origin point to be incorrect. Is there a formula we can apply that would find the correct x and y values to set on a click point for the CSS transform-orign property based on the current angle of the element?
I'm not too sure if this article is the same as mine: How we can calculate the correct x and y value for the rotated image?
This thing is driving me nuts. I made a JSFiddle:
https://jsfiddle.net/f251qL98/
The goal here is to make the element rotate around any point within the element that we click on. By default, the origin point is set at the center of the element. The first click works fine, but subsequent ones, the element rotates around the incorrect origin point.
But if we click on another part of the element, I'm not too sure where the origin would be located, especially if the object has been rotated. I'm sure it is some math triangle manipulation solution, but that is not my strong side. Anyhow, back to testing all try to test more possibilities.

Finding the position of an element from another

I would like to click on an element (without id) thanks to the coordinates of another (found with his id).
I am thinking of something like
.click(apple + offsetX)
.click(orange + offsetX)
I hope it's clear I am new to Javascript and testing.
Your question is not soclear but I think you want something just like this.
for apple element. calculate x position and y position of apple element and run this code;
var x = /*calculate x position of apple*/;
var y = /*calculate y position of apple*/;
document.elementFromPoint(x,y).click();
there is an example for you
https://codepen.io/lumosmind/pen/PoPGwZZ

Get the exact coordinates of a particular element itself with JQuery

I am trying to get the coordinates of a div with JQuery. I am currently using this method:
$("#draw_area").click(function (e) {
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
});
However, I realised that if I have html elements on top of the div "draw_area", it will give me different "y". I do not want that. What I want is to get the exact/relative coordinates of that particular div, and the coordinates are always the same regardless whether there are other elements
EDIT:
above the div or next to the div.
Can someone please tell me how I could achieve this? Any help will be appreciated. Thanks!
I think you're looking for .offset(), which gives you the position relative to the document, as opposed to .position(), which gives you the position relative to the offset parent.
$("#draw_area").click(function (e) {
var o = $(this).offset();
var x = o.left;
var y = o.top;
});

Javascript comparing mouse click to xy to that of button

I am trying to get the x and y of an html button to that of a mouseclick by the user, I am doing this as follows:
function buttonPressed(event, id){
var mainEvent = event ? event : window.event;
var mousex=event.clientX;
var mousey=mainEvent.screenY;
var y= $('#'+id).position();
var x= document.getElementById(id).offsetLeft;
console.log(y);
console.log(mousey);
This shows 2 different ways to get these value of both the button and the mouse (event.clientX,mainEvent.screenY,$('#'+id).position()(uses jquery),and offsetLeft).
However none of these techniques seem to work as I would like them to as the values do not line up ie when I click on the top left of the button the values are not the same or even similar. Additionally it seems like the difference changes, for example: if I have a button top left and one top right on the top left the values may differ by 100, whereas the bottom they will differ by -100. How can I acheive what I am wanting (to be able to compare the mousex and the button x)?
client X/Y Mouse pointer X/Y coordinate relative to window
offset X/Y Mouse pointer X/Y coordinate relative to element that fired the event
screen X/Y Relative to the top left of the physical screen/monitor
Thats why you are getting difference here
var mousex=event.clientX;
var mousey=mainEvent.screenY;
Use clientX for both

How to get the correct mouse position in relation to a div that has has a scale transform applied

I am using CSS transform scale to create a smooth zoom on a div. The problem is that I want to be able to get the correct mouse position in relation to div even when scaled up, but I can seem figure out the correct algorithm to get this data. I am retrieving the current scale factor from:
var transform = new WebKitCSSMatrix(window.getComputedStyle($("#zoom_div")[0]).webkitTransform);
scale = transform.a;
When I read the position of the div at various scale settings it seems to report the correct position, i.e. when I scale the div until is is larger the the screen the position left and top values are negative and appear to be correct, as does the returned scale value:
$("#zoom_div").position().left
$("#zoom_div").position().top
To get the current mouse position I am reading the x and y position from the click event and taking away the offset. This works correctly at a scale value of 1 (no scale) but not when the div is scaled up. Here is my basic code:
$("#zoom_div").on("click", function(e){
var org = e.originalEvent;
var pos = $("#zoom_div").position();
var offset = {
x:org.changedTouches[0].pageX - pos.left,
y:org.changedTouches[0].pageY - pos.top
}
var rel_x_pos = org.changedTouches[0].pageX - offset.x;
var rel_y_pos = org.changedTouches[0].pageY - offset.y;
var rel_pos = [rel_x_pos, rel_y_pos];
return rel_pos;
});
I have made several attempts at multiplying dividing adding and subtracting the scale factor to/from from the pageX / Y but without any luck. Can anyone help me figure out how to get the correct value.
(I have simplified my code from the original to hopefully make my question clearer, any errors you may find in the above code is due to that editing down. My original code with the exception for the mouse position issue).
To illustrate what I am talking about I have made a quick jsfiddle example that allows the dragging of a div using translate3d. When the scale is normal (1) the div is dragged at the point where it is clicked. When the div is scales up (2) it no longer drags correctly from the point clicked.
http://jsfiddle.net/6EsYG/12/
You need to set the webkit transform origin. Basically, when you scale up it will originate from the center. This means the offset will be wrong. 0,0 will start in the center of the square. However, if you set the origin to the top left corner, it will keep the correct coordinates when scaling it. This is how you set the origin:
#zoom_div{
-webkit-transform-origin: 0 0;
}
This combined with multiplying the offset by the scale worked for me:
offset = {
"x" : x * scale,
"y" : y * scale
}
View jsFiddle Demo
dont use event.pageX - pos.left, but event.offsetX (or for some browser: event.originalEvent.layerX
div.on('click',function(e) {
var x = (e.offsetX != null) ? e.offsetX : e.originalEvent.layerX;
var y = (e.offsetY != null) ? e.offsetY : e.originalEvent.layerY;
});
see my jsFiddle exemple: http://jsfiddle.net/Yukulele/LdLZg/
You may embed the scaled content within an iframe. Scale outside the iframe to enable scaled mouse events within the iframe as mouse events are document scope.

Categories