angularJS - getting x & y positions from mouseclick in div

M. Winterinho picture M. Winterinho · Jan 18, 2013 · Viewed 45.2k times · Source

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,
        })
}

Answer

Liviu T. picture Liviu T. · Jan 18, 2013

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>