I have a top div on the page with a height of 300px and items generated using ng-repeat. I want to apply the class "no_visible" to each span element if the text "Hello World" is partially or fully hidden under the top div. How can I achieve this?
var app = angular.module('plunker', []);
app
.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.items = [];
for(var i =0; i<100;i++){
$scope.items.push(i);
}
})
.directive('trackVisibility', function(){
function isVisible(el) {
var rect = el.getBoundingClientRect();
var clw = (window.innerWidth || document.documentElement.clientWidth);
var clh = (window.innerHeight || document.documentElement.clientHeight) ;
// checks if element is fully visible
//return (rect.top >= 0 && rect.bottom <= clh) && (rect.left >= 0 && rect.right <= clw);
// checks if part of element is visible
return (rect.left <= clw && 0 <= rect.right && rect.top <= clh && 0 <= rect.bottom);
}
var reg = [];
function register(element, fn) {
reg.push([element, fn]);
}
function deregister(element) {
reg = angular.filter(reg, function (item) {
return item[0] !== element;
});
}
angular.element(window).on('DOMContentLoaded load resize scroll', function () {
angular.forEach(reg, function (item) {
item[1](isVisible(item[0]));
});
});
return {
restrict: 'A',
link: function (scope, element, attrs, controller) {
register(element[0], function(isVisible){
scope.$apply(function(){
scope.isVisible = isVisible;
})
});
scope.$on('$destroy', function(){
deregister(element);
})
}
};
});
span {
display: block;
height: 30px;
border: 1px solid;
}
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85e4ebe2f0e9e4f7abeff6c5b4abb7abfd">[email protected]</a>" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div style="height:300px; width:300px; position: fixed; background: #000;">
</div>
<div style="margin-top:350px; position: absolute;">
<span style="float:left; clear: both; " ng-repeat="i in items" track-visibility>Hello {{name}} {{isVisible?'yes':'no'}}!</span>
</div>
</body>
</html>