8

I have a div with a scrollbar in it. Now I want to get an event, that triggers every time, the user scrolls.

Is that possible in AngularJS, or do I have to use jQuery for that?

Edit: I came up with following so far:

// JS
.directive('scroll', function() {
    return function(scope, element, attrs){

        angular.element(element).bind("scroll", function(){
            console.log(1);
        });
    };
});

// HTML
<div class="wrapper" style="height: 1550px" scroll>
[...]
</div>

But that does not work (I don't see any logs in my Firebug-Console).

3 Answers 3

16

Solution for Angular 1.6:

.directive("scroll", function () {
return {
  link: function(scope, element, attrs) {
      element.bind("wheel", function() {
         console.log('Scrolled below header.');
      });
  }
}

})

Use "wheel" instead of "scroll". It takes me few hours to find.

Sign up to request clarification or add additional context in comments.

1 Comment

We should use angular.element(document) instead of angular.element('html') : )
4

You would be using jquery for adding the event listener, and maybe inside an angularjs directive to attach it to an element.

page.html:

<div my-scroller>

myscroller.js:

app.directive('myScroller', function(){

    return {

        restrict: 'A',
        link: function(scope,elem,attrs){
            $(elem).on('scroll', function(evt){
               console.log(evt.offsetX + ':' + evt.offsetY);
            });
        }

    }

});

Edit: of course you don't even need to use jquery. Angular's jqLite suffices for this, you would just call element without the jquery wrapping:

elem.on('scroll', ...

4 Comments

Note that this doesn't necessarily use jQuery, it's using jqLite (docs.angularjs.org/api/ng/function/angular.element)
@NevilleS correct, I wrapped it inside $() so it uses jQuery.
You don't need to though; jqLite provides the on() method as well (with some restrictions), avoiding the need to include jQuery.
Thank you for your reply, @frankies. I edited my post and added the code, I already tried. If there is any chance to do it without jQuery, I would like to it without.
1

Sergey's answer helped me a little, but what ended up working for me was this:

.directive("scroll", function ($window) {
   return {
      link: function() {
         angular.element($window).bind("wheel", function() {
            console.log('Scrolling');
         });
      }
   }
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.