Skip to content

Instantly share code, notes, and snippets.

@tastywheat
Created December 22, 2013 00:37
Show Gist options
  • Save tastywheat/8077072 to your computer and use it in GitHub Desktop.
Save tastywheat/8077072 to your computer and use it in GitHub Desktop.
Angular directive: action on rollover element
<!doctype html>
<html ng-app='app'>
<head>
<style>
body{
height:5000px;
}
.block{
height:300px;
border: 1px solid #000;
margin-bottom: 50px;
}
</style>
</head>
<body ng-controller="defaultController">
<div class="block" bl-mark handle="first">
first
</div>
<div class="block second" bl-mark handle="second">
second
</div>
<div class="block" bl-mark handle="third">
third
</div>
<div class="block" bl-mark handle="fourth">
fourth
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('defaultController', function(){
});
app.factory('scrollService', function(){
var handlers = [];
main();
function main(){
var body = document.querySelector('body');
window.onscroll = function(){
publish(body.scrollTop);
}
}
function publish(scrollTop){
handlers.forEach(function(handler){
handler(scrollTop);
});
}
function subscribe(handler){
handlers.push(handler);
}
return {
publish: publish,
subscribe: subscribe
};
});
app.directive('blMark', function(scrollService){
return {
scope: {},
link: function(scope, element, attrs){
var rawElement = element[0];
var notified = false;
scrollService.subscribe(handler);
function handler(scrollTop){
if(!notified && scrollTop > rawElement.offsetTop){
notified = true;
//alert(attrs.handle);
console.log(attrs.handle);
}
else if(scrollTop < rawElement.offsetTop){
notified = false;
}
}
}
};
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment