2

I'm trying to execute some function while scrolling. Basically if a certain scroll position is met I want the app to do something.

Here some of the code:

  ionViewDidLoad() {
    this.content.ionScroll.subscribe((event) => {
      this.scrollPosition = event.scrollTop;
      if(this.scrollPosition >= 100){
        console.log("more than 100");
      }
      else {
        console.log("less than 100");
      }
    });
  }

It works as expected on web browsers or Android devices, it repeatedly runs the "console.log()"s within the condition while scrolling. On iOS, instead, it waits for the scroll to stop and then it does the console.log(). I was reading that on iOS javascript gets stopped while scrolling, for performance reasons. Is there a workaround for this?

leota
  • 1,636
  • 2
  • 13
  • 33
  • About a year ago I created [jquery-do-scroll](https://github.com/WashingtonGuedes/jquery-do-scroll) as workaround to this exactly case in iPad, though I'm not sure if it would work with ionic framework in a _natural_ way. Basically, this plugin uses touch events to scroll with some easy to use functions. – Washington Guedes Jun 12 '17 at 16:43
  • Have you tried using the https://github.com/ionic-team/cordova-plugin-wkwebview-engine plug-in? Scroll events should work as expected when using it. – z00bs Jun 15 '17 at 17:25
  • 1
    Actually I didn't, I'll try it out, thanks – leota Jun 15 '17 at 17:27

1 Answers1

0

Safari doesnt fire a scroll event until after the scroll is complete, so you'd have to do some custom event listening in this case.

Check out this post: javascript scroll event for iPhone/iPad?

It could be achieved like so:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

I would recommend creating a directive, using HostListener to listen for those two events.

Pezetter
  • 2,783
  • 2
  • 22
  • 40
  • Thanks, that was helpful, but the function "ScrollStart()" gets executed only if I keep my finger on the screen. If I swipe down and take my finger off the screen, it stops executing, while the view is still scrolling. I need to know the scroll position at every moment. Any advice? – leota Jun 13 '17 at 08:32
  • Then you'd have to listen for touchStart as well. https://developer.apple.com/documentation/webkitjs/touchevent – Pezetter Jun 13 '17 at 12:23
  • I read the docs, but all these events occurs only when the finger touches the surface. As soon as you take your finger off they stop firing, no matter if the view is still scrolling. Thanks anyway – leota Jun 15 '17 at 08:52