code everywhere

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".

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';
});

recent posts

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy