Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current position of an element in angularjs

I want to change the user interface on scrolling the page, and for that i want to get the position of div element (top and bottom), how can i do this in angularjs ? In the following code how can i get the top_position?

var w=angular.element($window);

w.bind('scroll', function(){

    var top_div=angular.element($('#top-div'));
    // now here what function should i use ?
    console.log("the top of the div having id top-div:"+**top_position**);

});
like image 577
PRASHANT KUMAR Avatar asked Jan 30 '16 10:01

PRASHANT KUMAR


2 Answers

you can get the DOM element in a link function of your directive and do with it wherever you want

scope: {...},
restrict: 'AE',
controller: function() {},
link: function($scope, elem, attrs) {
   var el = elem[0]; // elem - jQLite element, el - native DOM element
   console.log(el.getBoundingClientRect()); // the bounding rect of the element
}
like image 173
kirill.buga Avatar answered Oct 19 '22 05:10

kirill.buga


Basically you could use two options to get top position of desired element.

  1. .offset() which will give you position of element & can provide top & left position. But that does calculate with document height, not with the view-port height.
  2. .scrollTop() is method by you can get height relate to viewport(window). I think this is suitable thing to go.

Other than that I'd suggest you to move your code to directive, so that you can get better control over that DOM.

like image 2
Pankaj Parkar Avatar answered Oct 19 '22 04:10

Pankaj Parkar