14

In jQuery we can get position of an object with this:

$(this).position().left;

How can we get the current element position with AngularJS?

1 Answer 1

36

You can use prop() from angular jqlite. to select an element you can use querySelector() that returns first matching element or querySelectorAll() that return all matching element

angular.element(document.querySelector('yourelement')).prop('offsetLeft');

or if your "this" is valid dom element

angular.element(this).prop('offsetLeft');

Example for div

you can reference the DOM object with $event in html and pass it to the function on controller

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

in controller

$scope.myfunction = function($event){
 console.log(angular.element($event.target).prop('offsetLeft'));

}

Demo

app = angular.module('test',[]);
app.controller('testctrl',function($scope){

  
  $scope.myfunction = function($event){
    console.log($event);
 off =angular.element($event.target).prop('offsetLeft');
  angular.element($event.target).text(off)

}
  
});
.divvy{position:absolute; left:60px;
width:100px; background:red;
}
   

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div  ng-controller="testctrl" ng-app="test">
   <div class="divvy" ng-click="myfunction($event)" >Click to see position</div>
  </div>

6
  • Thanks for your answer. Can I use $scope to get the position? Dec 20, 2014 at 14:50
  • $scope is not valid Dom element you can use class ot tag name in querySelector('')
    – A.B
    Dec 20, 2014 at 14:51
  • are you using it in any click/hover event?
    – A.B
    Dec 20, 2014 at 14:56
  • Yes, I am using ng-click. Tried with your example, but I get undefined value. It would be great if you could give complete example on how to get position of an element being clicked. Thank you. Dec 20, 2014 at 14:59
  • Thanks for the example, but I still get undefined value Dec 20, 2014 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.