• This repository has been archived on 14/Jan/2020
  • Stars
    star
    280
  • Rank 142,642 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 11 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Get a callback when any element becomes visible in a viewport (body or custom viewport)

NOTE FROM MAINTAINER:

This library is no more required nowadays, you can now rely on the Intersection Observer API which is available in all modern browsers: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

/NOTE FROM MAINTAINER

inViewport devDependency Status

Know when an element is in the window viewport or a custom viewport.

Selenium Test Status

API

Immediate result

var inViewport = require('in-viewport');
var elem = document.getElementById('myFancyDiv');

var isInViewport = inViewport(elem); // returns `true` or `false`

alert('myFancyDiv is ' + isInViewport ? 'visible' : 'not visible' + ' in the window');

Using a callback

We watch for your element to enters the viewport and call your callback when it does.

var inViewport = require('in-viewport');
var elem = document.getElementById('myFancyDiv');

inViewport(elem, visible);

function visible(elt) {
  // elt === elem
  alert(elt.id + ' is visible in the window!');
}

The first callback argument is always the element that entered the viewport.

Callback watcher API

The callback is called only one time, when the element is in the viewport for the first time. At any time you can rewatch or stop watching, by using the watch and dispose API.

var inViewport = require('in-viewport');
var elem = document.getElementById('myFancyDiv');
var count = 0;
var timer;

var watcher = inViewport(elem, visible);

function visible() {
  count++;
  timer = setTimeout(watcher.watch, 1000);
}

setTimeout(function(){
  watcher.dispose();
  clearTimeout(timer);
  alert('myfancyDiv was visible '+count+' seconds in the last 10 seconds!');
}, 10000);

A custom container

By default, we use the current window as the reference viewport. But you can also specify another element as a reference viewport.

var inViewport = require('in-viewport');
var customContainer = document.getElementById('myFancyContainer');
var elem = document.getElementById('myFancyDiv');

inViewport(elem, { container: customContainer }, visible);

function visible() {
  alert('myfancyDiv is visible in the `customContainer`!');
}

Specifying an offset

By default, when your element precisely enters the viewport, you get a callback.

But maybe you want to know when your element is soon-to-be-shown in the viewport?

Use the offset param for that!

var inViewport = require('in-viewport');
var elem = document.getElementById('myFancyDiv');

inViewport(elem, { offset: 300 }, visible);

function visible() {
  alert('myfancyDiv is visible in the `customContainer`!');
}

When your element is near 300px of the viewport, you get your callback / true result.

Specifying debounce value

Currently, scroll and resize events are called every 15ms, but there are situations where larger value like 300ms is more sensible, e.g. image lazyload, where you probably want to wait for user to stop with scrolling before loading every image that comes into viewport.

You can change that with debounce param.

var inViewport = require('in-viewport');
var elem = document.getElementById('myFancyDiv');

inViewport(elem, { debounce: 300 }, visible);

function visible() {
  alert('myfancyDiv is visible in the `customContainer`!');
}

Failsafe check

By default, inViewport does a failsafe to handle display manipulation that does not throw an event. It works with a setInterval performed every 150ms.

One of the situations where this is useful is when you have a hidden parent containing elements; when the parent becomes visible, we have no event that the children became visible. If you handle cases like this by yourself in different part of your codebase (e.g. you have callback which is active when parent becomse visible), you can turn it off with failsafe param.

var inViewport = require('in-viewport');
var elem = document.getElementById('myFancyDiv');

inViewport(elem, { failsafe: false }, visible);

function visible() {
  alert('myfancyDiv is visible in the `customContainer`!');
}

Dynamic element creation (document.createElement)

If you are creating elements dynamically, be sure to call inViewport when the element is in the DOM.

Otherwise it may fail on old browsers.

We check for newly visible elements on scroll or resize.

We use MutationObserver to listen for newly added DOM nodes that were previously registered with in-viewport.

MutationObserver is not compatible with old browsers.

That is why, if you need old browsers full compatibility, you should call in-viewport after inserting elements in the DOM.

Use cases

  • Images, iframes, widgets lazyloader
  • infinite scroll
  • loading widgets only when needed

Quirksmode

Be sure to be in standards-compliant mode.

Quirks mode is not supported since most browsers will report invalid values for window viewport.

Developing

Launch the dev server:

npm run dev

Browse to http://localhost:8080/__zuul.

Tests are written with mocha.

Building

We provide a pre-built version of in-viewport in build/in-viewport.min.js.

But you can build your own:

npm run build

You get the build in build/in-viewport.min.js.

Please consider using browserify.

License

Copyright (c) 2013-2016 Vincent Voyer

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

gifify

😻 Convert any video file to an optimized animated GIF.
JavaScript
6,088
star
2

iron-session

πŸ›  Secure, stateless, and cookie-based session library for JavaScript
TypeScript
3,276
star
3

lazyload

πŸš… Lazyload images, iframes, widgets with a standalone JavaScript lazyloader
JavaScript
942
star
4

tzdb

πŸ•° Simplified, grouped and always up to date list of time zones, with major cities
JavaScript
629
star
5

sourcekarma

Discover how people react to you on GitHub πŸ‘
JavaScript
101
star
6

javascript-library-template

JavaScript library template to focus on ⌨️ coding, πŸ™Œ collaborating and πŸš€ shipping
JavaScript
80
star
7

npm-pkgr

Cache `npm install` results by hashing dependencies
JavaScript
73
star
8

nextjs-vercel-aws-cdk-example

Example Next.js project deployed on Vercel with AWS services for database, cron jobs and asynchronous jobs
JavaScript
70
star
9

docker-selenium-firefox-chrome-beta

A Dockerfile starting a selenium standalone server with Chrome and Firefox beta
Shell
67
star
10

iron-store

🧿 in-memory, signed and encrypted JavaScript store
JavaScript
65
star
11

aws-lambda-nodejs-webpack

Ξ» CDK Construct to build Node.js AWS lambdas using webpack
TypeScript
31
star
12

analytics.js-loader

Asynchronously load segment.com analytics.js with an npm module
JavaScript
29
star
13

concat-files

[DEPRECATED] Concatenate files asynchronously with node.js
JavaScript
26
star
14

zorgs

πŸ¦‘ Command line tool displaying GitHub organizations stats
JavaScript
18
star
15

ansible-archee

dotfiles on steroids
Python
17
star
16

localenvify

localenv and envify combined as a browserify transform
JavaScript
14
star
17

chainit

Turn an asynchronous JavaScript api into an asynchronous chainable JavaScript api
JavaScript
12
star
18

selenium-runner

Run a [url/JSTest, ..] combo in selenium grid, in parallel
JavaScript
10
star
19

mocha-browse

Launch headless browsers on any mocha tests webpage, get results in console
JavaScript
9
star
20

node-whereis

Simply get the first path to a bin on any system
JavaScript
7
star
21

typescript-library-template

TypeScript library template to focus on ⌨️ coding, πŸ™Œ collaborating and πŸš€ shipping
TypeScript
7
star
22

project-name

description
JavaScript
5
star
23

tokenify

🎰 Interactive command line tool to easily get refresh tokens for Spotify API
JavaScript
5
star
24

coronamaison

🎨 All the drawings from the #coronamaison hashtag on Twitter
JavaScript
5
star
25

almanak

WIP Google Calendar like component for React
TypeScript
5
star
26

azure-sb-queue-watcher

Job worker around Azure Service Bus Queues
JavaScript
4
star
27

forkie

Forkie is a graceful process manager for Node.js: start/stop/working?
JavaScript
4
star
28

knex-typescript-migrations-esm

TypeScript
3
star
29

offline-docs

Always get some documentation on the modules you use, even offline
CSS
3
star
30

b64-bench

JavaScript
2
star
31

kcnb1-france.org

Repository for Association KCNB1 France website
PHP
2
star
32

www.berlisco.com

CTRL+W
JavaScript
2
star
33

cron-example

CSS
2
star
34

aws-lambda-nodejs-performance

Example of performance issue of aws-lambda-nodejs
JavaScript
2
star
35

vercel-test-workspaces

JavaScript
1
star
36

test-favicon

Vue
1
star
37

test-post-body

JavaScript
1
star
38

example-empty-project

1
star
39

vvo

1
star
40

npm-test-pre-push

Install a git pre-push hook launching `npm test`
JavaScript
1
star
41

test-babel-node-configuration-file

JavaScript
1
star
42

go-ghoauth

Two steps process for github access_token creation
Go
1
star
43

test-next-broken-packagelock

JavaScript
1
star
44

knex-pool-require-cache-issue

Demo of knex pool issue when combined with delete require.cache
JavaScript
1
star
45

deploy-summary-test

CSS
1
star
46

express-minimal-app

basic express app, production ready
JavaScript
1
star
47

nextjs-jobs

JavaScript
1
star
48

emoshort

Emoji to short name converter
JavaScript
1
star
49

swc-maximum-call-stack-error

TypeScript
1
star
50

test-nextjs-routes-bug-locales

JavaScript
1
star