Repository: russellgoldenberg/enter-view
Branch: master
Commit: ec856046f026
Files: 8
Total size: 13.0 KB
Directory structure:
gitextract_ssz2htd4/
├── .eslintrc
├── .gitignore
├── .nojekyll
├── LICENSE
├── README.md
├── enter-view.js
├── index.html
└── package.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintrc
================================================
{
"extends": ["airbnb-base", "prettier"],
"plugins": ["prettier"],
"rules": {
"quotes": [1, "single"],
"no-tabs": 0,
"indent": ["error", "tab"]
}
}
================================================
FILE: .gitignore
================================================
.DS_Store
node_modules
package-lock.json
================================================
FILE: .nojekyll
================================================
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2022 Russell Samora
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.
================================================
FILE: README.md
================================================
# enter-view
Dependency-free JavaScript library to detect when element enters into view. [See demo](https://russellsamora.github.io/enter-view/). It uses requestAnimationFrame in favor of scroll events for less jank. Less than 1kb minified + gzipped.
## Installation
Old school (exposes the `enterView` global):
```html
```
New school:
```sh
npm install enter-view --save
```
And then import/require it:
```js
import enterView from 'enter-view'; // or...
const enterView = require('enterView');
```
## Usage
```
enterView({
selector: '.class-name',
enter: function(el) {
el.classList.add('entered');
}
});
```
```
enterView({
selector: '.class-name',
enter: function(el) {
el.classList.add('entered');
},
exit: function(el) {
el.classList.remove('entered');
},
progress: function(el, progress) {
el.style.opacity = progress;
},
offset: 0.5, // enter at middle of viewport
once: true, // trigger just once
});
```
## Options
#### selector: [string or array of elements] _required_
Takes a class, id, or array of dom elements.
#### enter: [function] _optional_
Callback function that returns the element that was entered.
#### exit: [function] _optional_
Callback function that returns the element that was exited.
#### progress: [function] _optional_
Callback function that returns the element that was progressed through, and a value between 0 and 1 of how far through the element progress has been made.
#### offset: [number] _optional_ (defaults to 0)
A value from 0 to 1 of how far from the bottom of the viewport to offset the trigger by. 0 = top of element crosses bottom of viewport (enters screen from bottom), 1 = top of element crosses top of viewport (exits screen top).
#### once: [boolean] _optional_ (defaults to false)
Whether or not to trigger the callback just once.
## Contributors
- [Russell Samora](https://github.com/russellsamora)
- [Jonathan Soma](https://github.com/jsoma)
================================================
FILE: enter-view.js
================================================
/*
* enter-view.js is library
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
} else {
window.enterView = factory.call(this);
}
})(() => {
const lib = ({
selector,
enter = () => {},
exit = () => {},
progress = () => {},
offset = 0,
once = false
}) => {
let raf = null;
let ticking = false;
let elements = [];
let height = 0;
function setupRaf() {
raf =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
return setTimeout(callback, 1000 / 60);
};
}
function getOffsetHeight() {
if (offset && typeof offset === 'number') {
const fraction = Math.min(Math.max(0, offset), 1);
return height - fraction * height;
}
return height;
}
function updateHeight() {
const cH = document.documentElement.clientHeight;
const wH = window.innerHeight || 0;
height = Math.max(cH, wH);
}
function updateScroll() {
ticking = false;
const targetFromTop = getOffsetHeight();
elements = elements.filter(el => {
const { top, bottom, height } = el.getBoundingClientRect();
const entered = top < targetFromTop;
const exited = bottom < targetFromTop;
// enter + exit
if (entered && !el.__ev_entered) {
enter(el);
el.__ev_progress = 0;
progress(el, el.__ev_progress);
if (once) return false;
} else if (!entered && el.__ev_entered) {
el.__ev_progress = 0;
progress(el, el.__ev_progress);
exit(el);
}
// progress
if (entered && !exited) {
const delta = (targetFromTop - top) / height;
el.__ev_progress = Math.min(1, Math.max(0, delta));
progress(el, el.__ev_progress);
}
if (entered && exited && el.__ev_progress !== 1) {
el.__ev_progress = 1;
progress(el, el.__ev_progress);
}
el.__ev_entered = entered;
return true;
});
if (!elements.length) {
window.removeEventListener('scroll', onScroll, true);
window.removeEventListener('resize', onResize, true);
window.removeEventListener('load', onLoad, true);
}
}
function onScroll() {
if (!ticking) {
ticking = true;
raf(updateScroll);
}
}
function onResize() {
updateHeight();
updateScroll();
}
function onLoad() {
updateHeight();
updateScroll();
}
function selectionToArray(selection) {
const len = selection.length;
const result = [];
for (let i = 0; i < len; i += 1) {
result.push(selection[i]);
}
return result;
}
function selectAll(selector, parent = document) {
if (typeof selector === 'string') {
return selectionToArray(parent.querySelectorAll(selector));
} else if (selector instanceof NodeList) {
return selectionToArray(selector);
} else if (selector instanceof Array) {
return selector;
}
}
function setupElements() {
elements = selectAll(selector);
}
function setupEvents() {
window.addEventListener('resize', onResize, true);
window.addEventListener('scroll', onScroll, true);
window.addEventListener('load', onLoad, true);
onResize();
}
function init() {
if (!selector) {
console.error('must pass a selector');
return false;
}
setupElements();
if (!elements || !elements.length) {
console.error('no selector elements found');
return false;
}
setupRaf();
setupEvents();
updateScroll();
}
init();
};
return lib;
});
================================================
FILE: index.html
================================================
enter-view.js
Enter-view.js Demo
Dependency-free JavaScript library to detect when element enters into view
Start scrolling to see examples.
Default (no offset)
enterView({
selector: '.block-a',
enter: function(el) {
el.classList.add('entered');
}
});
50% offset
enterView({
selector: '.block-b',
offset: 0.5,
enter: function(el) {
el.classList.add('entered');
}
});
75% offset, trigger every time
var count = 0;
enterView({
selector: '.block-c',
offset: '0.75,
enter: function(el) {
el.classList.add('entered');
count += 1;
el.querySelector('span').innerText = count;
}
});
Multiple elements, 50% offset
enterView({
selector: '.block-d',
offset: 0.5,
enter: function(el) {
el.classList.add('entered');
}
});
Exit element, 50% offset
enterView({
selector: '.block-e',
offset: 0.5,
enter: function(el) {
el.classList.add('entered');
},
exit: function(el) {
el.classList.remove('entered');
},
});
Progress increments, 50% offset
enterView({
selector: '.block-f',
offset: 0.5,
enter: function(el) {
el.classList.add('entered');
},
progress: function(el, progress) {
var p = el.querySelector('.progress')
p.innerText = progress.toFixed(2);
}
});
================================================
FILE: package.json
================================================
{
"name": "enter-view",
"version": "2.0.1",
"description": "Dependency-free JavaScript library to detect when element enters into view",
"main": "enter-view.min.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"enter",
"view",
"viewport",
"scroll",
"into",
"element"
],
"author": "Russell Samora",
"license": "MIT",
"devDependencies": {
"eslint": "^2.5.3",
"eslint-config-airbnb": "^6.2.0",
"eslint-plugin-react": "^4.2.3",
"terser": "^5.5.1"
},
"dependencies": {}
}