Luis Masuelli Luis Masuelli - 1 year ago 95
AngularJS Question

How do I read mouse position in angularjs when a click is made?

I want to get the in-element (x, y) position of a

ed element. Using
gets transformed by the page scroll. Using
is not scroll-dependent, but it is absolute. Those four properties belong to the
object, available inside the
directive. How would I calculate the in-element x and y?

In jQuery I'd do something like:

var parentOffset = $(this).parent().offset();
//or $(this).offset(); if you really just want the current element's offset
var relX = e.pageX - parentOffset.left;
var relY = e.pageY -;

But now, I want to do it in angularjs (i.e. inside a
, not inside a postLink function). What is a good way to do it? Is it safe to do the same but using
? Or is there another way of calculating the values I need?

Edit Clarifying: In a controller, I'd try:

$scope.onClick = function($event) {
//currently I can...
var pageX = $event.pageX;
var pageY = $event.pageY;

But I need to transform those coordinates to clicked-element related coordinates, since those elements are absolute. Consider an appropiate HTML:

<div ng-click="onClick($event)">Nestor Kirchner</div>

Answer Source

this should get you started:

$scope.doClick = function(event){

    var x = event.x;
    var y = event.y;
    var offsetX = event.offsetX;
    var offsetY = event.offsetY;

    // you have lots of things to try here, not sure what you want to calculate
    console.log(event, x, y, offsetX, offsetY);

and HTML:

<div ng-click="doClick($event)"></div>

Please clarify what you are trying to calculate? Some examples?

Sample code:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download