Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

element-within-viewport

niksy2.3kMIT3.0.1

Check if element is within viewport.

viewport

readme

element-within-viewport

Build Status BrowserStack Status

Check if element is within viewport.

Convenient wrapper around viewprt supporting debounced listeners.

Install

npm install element-within-viewport --save

Usage

import elementWithinViewport from 'element-within-viewport';

elementWithinViewport(document.querySelector('#jackie'), {
    onEnter: (element) => {
        // Element in viewport!
    }
});

API

elementWithinViewport(element, options)

Check if element is within viewport and calls proper callback.

element

Type: Element

Element to check.

options

Type: object

Property Type Default value Description
threshold number 0 Positive value in pixels which will signal plugin to check for element presence earlier in document.
scrollResizeHandler Function (handler) => handler Window scroll and resize event handler. Useful if you want to use throttle or debounce methods on those events. Should return new handler (original or wrapped).
onEnter Function () => {} Callback to execute if element is within viewport.
onExit Function () => {} Callback to execute if element exits viewport.
once boolean false If true, will call onEnter only once.

instance.destroy()

Destroy instance.

FAQ

Throttling and debouncing scroll and resize event

If you want to throttle or debounce scroll and resize events, modify handler with scrollResizeHandler property.

import { debounce } from 'throttle-debounce';

elementWithinViewport(document.querySelector('#jackie'), {
    scrollResizeHandler: (handler) => debounce(300, handler)
});

Browser support

Tested in Edge 15, Chrome 88 and Firefox 86, and should work in all modern browsers.

Test

For automated tests, run npm run test:automated (append :watch for watcher support).

License

MIT © Ivan Nikolić

changelog

Changelog

Unreleased

3.0.1 - 2021-05-04

Fixed

  • Properly resolve ES module imports

3.0.0 - 2021-05-04

Changed

  • Update viewprt

Removed

  • Breaking: Drop IE support, supported browser is Edge 15+
  • Fallback support

2.0.0 - 2020-02-20

Changed

  • Abstract scroll and resize event handling, so events could be wrapped with more functionality (e.g. throttle)

Added

  • scrollResizeHandler property

Removed

  • debounce property

1.3.0 - 2019-07-22

Changed

  • Update viewprt

1.2.1 - 2019-05-17

Changed

  • Upgrade package

1.2.0 - 2019-05-17

Changed

  • Add support for onExit method
  • Upgrade package

1.1.1 - 2019-01-28

  • Make package environment agnostic by using global instead of window

1.0.0 - 2019-01-09

Added

  • Initial stable implementation