@1eeing/scroll-listener
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-beta.1 • Public • Published

scrollListener

Do everything you want on scroll event. Such as lazy load , upload data.

Installation

npm install --save @1eeing/scroll-listener

Usage

// js
import { createListener } from '@1eeing/scroll-listener';

// When domContentLoaded has triggered.
const listener = createListener({
  positions: ['main'],
  actions: [
    () => {
      console.log('The element which id is main has scrolled to top of the screen.')
    }
  ]
})

listener.start();

// When dom is removed
listener.stop();
<!-- html -->
<body>
  <div id='main'></div>
</body>

If you are using React, you can use like this.

import React, { useEffect } from 'react';
import { createListener } from '@1eeing/scroll-listener';

const App = () => {
  useEffect(() => {
    const listener = createListener({
      positions: ['main'],
      actions: [
        () => {
          console.log('The element which id is main has scrolled to top of the screen.')
        }
      ]
    })

    listener.start();
    return () => listener.stop();
  }, [])

  return (
    <div>
      <div id='main'>
        Hello world.
      </div>
    </div>
  )
}

export default App;

Options

positions

type: string[] The id of the element you want to listen.

actions

type: ((id: string, offsetTop: number) => void)[] The action of the element you want to listen. Triggerd when the element scrolls to the top of the screen by default. One-to-one correspondence with postions.

when target is passed in, the action will be triggerd when the element scrolls to the top of the target.

triggerType?

type: 'appeard' | 'appearing' | 'once' Control when to trigger action. Default is once.

delayType?

type: 'throttle' | 'debounce' Delay your action function. Default is undefined.

delay?

type: number Only worked when delayType is passed in. Default is 500 ms.

offset?

type: number Offset from the top of the screen or target.

target?

type: string The target element'id you want to listen. Default the target is window.

needRequestIdleCallback?

type: boolean Use requestIdleCallback to trigger action. See detail https://developer.mozilla.org/zh-CN/docs/Web/API/Window/requestIdleCallback[https://developer.mozilla.org/zh-CN/docs/Web/API/Window/requestIdleCallback]. Default is false.

TODO

Package Sidebar

Install

npm i @1eeing/scroll-listener

Weekly Downloads

2

Version

1.0.0-beta.1

License

ISC

Unpacked Size

10.7 kB

Total Files

10

Last publish

Collaborators

  • 1eeing