ERIK_SON
ERIK_SON

Reputation: 399

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?

Upvotes: 2

Views: 93

Answers (1)

Rino Raj
Rino Raj

Reputation: 6264

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.

Upvotes: 3

Related Questions