code everywhere
technology, web services and applications

web page scroll event with angularJS

posted on January 12, 2015, 5:48 pm in js

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(
scopeelementattrs) {
        var 
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".

recent posts

< back