Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get x and y coordinates on mouse click

I have a little div tag that when I click it (onClick event), it will run the printMousePos() function. This is the HTML tags:

<html>     <header>         <!-- By the way, this is not the actual html file, just a generic example. -->         <script src='game.js'></script>     </header>     <body>         <div id="example">             <p id="test">x: , y:</p>         </div>     </body> </html> 

This is the printMousePos function in a seperate .js file:

function printMousePos() {     var cursorX;     var cursorY;     document.onmousemove = function(e){     cursorX = e.pageX;     cursorY = e.pageY; }     document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY; } 

Yes, the function actually works (it knows when you click it and all), but it returns undefined for both x and y, so I'm assuming that the get x and y code in the function is incorrect. Any Ideas? I also know there isn't any built in functions within javascript itself to return the x and y like in java, ex.. would there be a way to do it with say JQuery or php? (avoid those if possible though, javascript would be best). Thanks!

like image 309
Bryce Hahn Avatar asked May 19 '14 18:05

Bryce Hahn


People also ask

How do I get my mouse to click coordinates?

The position of x-coordinate of the mouse click is found by subtracting the event's x position with the bounding rectangle's x position. The x position of the event is found using the 'clientX' property. The x position of the canvas element, i.e. the left side of the rectangle can be found using the 'left' property.

How do you simulate a click using X and Y coordinates in JavaScript?

To simulate a click by using x, y coordinates in JavaScript, we can call the initMouseEvent method. const click = (x, y) => { const ev = document. createEvent("MouseEvent"); const el = document. elementFromPoint(x, y); ev.

Which method is used to get the Y coordinate of the point where user have clicked using mouse button?

Simple answer #1 use offsetX and offsetY offsetX; const y = e. offsetY; });


1 Answers

Like this.

function printMousePos(event) {    document.body.textContent =      "clientX: " + event.clientX +      " - clientY: " + event.clientY;  }    document.addEventListener("click", printMousePos);

MouseEvent - MDN

MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.

MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.

like image 67
Jonathan Avatar answered Sep 23 '22 20:09

Jonathan