AngularJS How to watch offset top position of elements? -
how watch offset top position (of each element) , if distance top screen border lower 100 px, need hide div. (each div can move on page). please write angular directive.
i can't watch each element top offset.
var app = angular.module('app', []); app.app.directive('blah', function() { return { restrict: 'a', link: function(scope, element) { element.show(); scope.$watch(function() { return element.offset().top > 120 }, function(outofborder) { if (outofborder) { element.hide() console.log(outofborder) } else { element.show() console.log(outofborder) } }); } } });
.all { height: 100px; width: 300px; border:1px solid; overflow: scroll; } .elements { height: 30px; width: 300px; border:1px solid red; float: left; clear: both; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div class="all" ng-app="app"> <div class="elements" blah></div> <div class="elements" blah></div> <div class="elements" blah></div> <div class="elements" blah></div> <div class="elements" blah></div> <div class="elements" blah></div> <div class="elements" blah></div> <div class="elements" blah></div> </div>
you add watcher function (not tested + need renaming):
angular.module('blah').directive('blah', function() { return { restrict: 'a', link: function(scope, element) { scope.$watch(function() { return element.offset().top < 100 }, function(outofborder) { if (outofborder) { element.hide() } else { element.show() } }); } } });
the reason why code not working value passed $watch
evaluated before $watch
executed. result, watch top offset on element @ time link executed - constant number.
edit:
if elements not absolutely positioned, calling hide cause remaining elements move make elements hidden. in case use element.addclass('invisible')
, element.removeclass('invisible')
instead of hiding , showing , define css class as:
.invisible { visibility: hidden; }
changed visibility not affect other element position.
Comments
Post a Comment