web page scroll event with angularJS
posted on January 12, 2015, 5:48 pm in
Use AngularJS to watch for a page scroll event and modify an elements CSS. This directive will toggle a "scrolled" class based on a scroll distance of 100px.
app.directive("scroll", ['$window', function($window) {
return function(scope, element, attrs) {
var w = angular.element($window);
w.bind("scroll", function() {
if (!('pageYOffset' in this))
w.unbind("scroll");
if (this.pageYOffset >= 100) {
element.addClass('scrolled');
} else {
element.removeClass('scrolled');
}
scope.$apply();
});
};
}]);
Usage
Use in your page:
<div class="header" scroll>...</div>
Which after 100px will get class="scrolled".
Not Using Angular?
Heres the pure JS way to do it, targeting the .topbar class and 65px:
window.addEventListener('scroll', function(e) {
var top = document.getElementsByClassName('topbar')[0];
if( this.pageYOffset >= 65 )
top.className = 'topbar sticky';
else
top.className = 'topbar';
});