Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularJS - getting x & y positions from mouseclick in div

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,         }) } 
like image 525
M. Winterinho Avatar asked Jan 17 '13 23:01

M. Winterinho


2 Answers

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> 
like image 108
Liviu T. Avatar answered Sep 23 '22 04:09

Liviu T.


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); } 
like image 20
Dudu Madeira Avatar answered Sep 22 '22 04:09

Dudu Madeira