DEV Community

HarmonyOS
HarmonyOS

Posted on

How to monitor the scroll state of a web component

Read the original article:How to monitor the scroll state of a web component

Context

onScroll: Notifies the global scroll position of the webpage. It informs about the global scroll position of the page; changes in local scroll positions do not trigger this callback. To determine if the page is globally scrolling, print window.pageYOffset or window.pageXOffset before and after scrolling. If it is a global scroll, the values of window.pageYOffset or window.pageXOffset will change before and after scrolling; otherwise, they remain unchanged.

onWillScroll: A scroll event callback triggered before the Scroll event. It provides the offset that the current frame is about to scroll, the current scroll state, and the source of the scroll operation. The offset in the callback is the calculated value of the offset that is about to be scrolled, not the final actual scroll offset. The return value of this callback can specify the offset that Scroll is about to scroll.

Conditions for triggering this event:

  • Triggered when the scroll component initiates a scroll, supporting other input settings that trigger scrolling such as keyboard and mouse operations.
  • Triggered by calling the scroll controller API interface.
  • Boundary bounce.

Description

How to monitor the scroll state of a Web component? For example, in a List component, you can listen to the onWillScroll callback to know the current scroll state of the component.

Solution

In web components, you can listen for scroll events using the onScroll method. When the page is scrolled, it triggers an event where you can execute custom logic, such as logging or performing other operations.

Reference code:

import { webview } from '@kit.ArkWeb';

@Entry
@Component
struct WebPage {
  controller: webview.WebviewController = new webview.WebviewController();
  // allOffset: Vertical scroll offset
  allOffSet: number = 0;

  build() {
    Column() {
      Web({
        src: 'www.example.com',
        controller: this.controller
      })
        .javaScriptAccess(true)
        .domStorageAccess(true)
        .verticalScrollBarAccess(true)
        .onScroll((event) => {
          // yOffset: The vertical scroll offset for the current scrolling operation.
          if (event.yOffset > this.allOffSet) {
            console.info('Decline');
          }
          if (this.allOffSet > event.yOffset) {
            console.info('Swipe up');
          }
          this.allOffSet = event.yOffset;
        });
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Written by Emine Inan

Top comments (0)