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-clicked 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:

    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 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>
Problem courtesy of: Luis Masuelli


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:

Solution courtesy of: SoluableNonagon


It will not work in mozilla firefox. For mozilla to work use,

var offsetX = event.originalEvent.layerX;
var offsetY = event.originalEvent.layerY;

Discussion courtesy of: Arjun

This recipe can be found in it's original form on Stack Over Flow.