39

I made a function that should add an item on the position I clicked inside a div. Now the problem with this function is, every time I click, it takes the x & y position of the document, not the x & y position inside the div. So what I actually want, is that the top-left corner of my div should give x=0 & y=0, but I don't know if this is possible? And I guess there is another way to do this..

$scope.addOnClick = function(event) {
        $scope.items.push( {
            "label": "Click",
            "value": 100,
            "x": event.x-50,
            "y": event.y-50,
        })
}
mwinter
  • 596
  • 2
  • 5
  • 14

3 Answers3

62

You need to change event.x to event.offsetX and event.y to event.offsetY

You didn't add the template definition but I'll add it just in case:

<div ng-click="addOnClick($event)"></div>
Liviu T.
  • 23,584
  • 10
  • 62
  • 58
  • That's exactly what I was looking for! I knew it would be something as easy as that :D & yeah, I already added the template definition, but I was sure everything was alright there.. Thanks alot mate! – mwinter Jan 17 '13 at 23:42
  • 18
    Be careful Firefox doesn't have offsetX. [Use layerX for Firefox.](http://stackoverflow.com/questions/8878471/return-coordinates-of-mouse-click-on-html5-canvas-using-javascript-mouse-events) – Endy Tjahjono Jun 06 '13 at 04:14
  • Firefox now has `offsetX` and `offsetY`, but they do not seem right. – trysis Oct 27 '15 at 22:53
5

In html file, use:

<div (click)="test($event)"></div>

And in the function in the ts file::

function test(e){
 console.log(e.clientX);
 console.log(e.clientY);
}
Dudu Madeira
  • 51
  • 1
  • 3
-1

For those on angular who are using dragging libraries and want the position of the element that was dragged:

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

and in the controller

$scope.onDrag($event){
      console.log("X ->",$event.originalEvent.pageX,"Y ->",$event.originalEvent.pageY)

 }
Dr Manhattan
  • 13,537
  • 6
  • 45
  • 41