Luis Masuelli Luis Masuelli - 2 months ago 6
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

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

In jQuery I'd do something like:

$("#something").click(function(e){
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 - parentOffset.top;
});


But now, I want to do it in angularjs (i.e. inside a
controller
, not inside a postLink function). What is a good way to do it? Is it safe to do the same but using
angular.element
? 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

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: http://plnkr.co/edit/TnhEliSUgChCaMN4gmYn?p=preview