3

I am trying to get the position of an element in a html page using $document.find. But, it is always undefined.

Here is my code.

angular.module('MyApp', []).
controller('myController', function($scope, $document) {

var element = $document.find('my_element');
console.log(element.prop('offsetTop'));
console.log(element.offsetTop);
});

And this is html page.

<div ng-app="MyApp" ng-controller="driversController">
  <div id="my_element">Looping with ng-repeat:</div>
  .......
</div>

I do not want to use jquery along with angularjs. P;ease suggest a way to do this in angularjs.Thanks

Mukund Gandlur
  • 861
  • 1
  • 12
  • 35

3 Answers3

5

Use jquery .offset() to find the position.

var offSet = $("#my_element").offset();
console.log(offSet.top);

Example : https://jsfiddle.net/o9krfznt/1/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26
  • It works. But I did not want to use jquery along with angularjs. How can I do this in strict angularjs? – Mukund Gandlur Mar 15 '16 at 19:24
  • @MukundGandlur you tagged angularjs, also perhaps you should append your question to say specifically not to use angularjs – Tyler Cowan Mar 15 '16 at 19:27
  • 1
    @MukundGandlur: If you are looking for pure angular solution , you might wanna take a look at this : http://stackoverflow.com/questions/18953144/how-do-i-get-the-offset-top-value-of-an-element-without-using-jquery. Also remove the tag jquery from the question tag. – DinoMyte Mar 15 '16 at 19:29
  • Marked this as answer because, the post in your comment helped me. – Mukund Gandlur Mar 16 '16 at 05:59
2

By having vanilla JavaScript, you could access offset values from DOM by doing element[0].

var element = $document.find('my_element');
console.log(element.prop('offsetTop'));
console.log(element[0].offsetTop);
console.log(element[0].offsetLeft);
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

You can loop through each element in page until you get to the element you want.

        function left_on(el)
        {    
                for (var lx=0, ly=0;
                     el != null;
                     lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
            return lx  ;// or ly 
        }
Reznicencu Bogdan
  • 902
  • 2
  • 11
  • 28