viewability
Version:
Returns how viewable an element is
94 lines (67 loc) • 2.92 kB
Markdown
# viewability
Browser package to check if the element is on screen without dependencies. Or you can call it visibility.
[](https://travis-ci.org/kahwee/viewability)
[](https://coveralls.io/github/kahwee/viewability?branch=master)
[](https://www.npmjs.com/package/viewability)
[](https://greenkeeper.io/)
[](https://david-dm.org/kahwee/viewability#info=devDependencies)
[](https://github.com/feross/standard)
No dependencies.
```js
var vertical = require("viewability/vertical");
vertical(document.getElementById("blue-box"));
// return {value: 1, state: "EL_IS_WITHIN_VERTICAL_VIEW"}
```
Use `'viewability/horizontal'` for corresponding view.
# Demo
Both source code are in the `gh-pages` branch.
[Draggable-based example](https://kahwee.github.io/viewability/)
[Timer-based example](https://kahwee.github.io/viewability/timer.html)
# Installation
- [npm](https://www.npmjs.org/): `npm install --save viewability`
- Direct download the latest version: https://github.com/kahwee/viewability/releases
- [jsDelivr CDN](http://www.jsdelivr.com/#!viewability): `<script src="https://cdn.jsdelivr.net/npm/viewability@VERSION/dist/viewability.min.js"></script>`
# Usage
## `viewability` package through CDN:
Loading it directly to the browser with `viewability` exposed to the window:
```html
<script src="https://cdn.jsdelivr.net/npm/viewability@latest/dist/viewability.min.js"></script>
<script>
var v = viewability.vertical(document.getElementById('red-box'));
console.log(v);
// return {value: 0.83, state: "EL_IS_WITHIN_VERTICAL_VIEW"}
</script>
```
## Using Common JS:
Finding out if the element is 100% on screen and using Common JS:
```js
var v = require("viewability");
var el = document.getElementById("blue-box");
if (v.isElementOnScreen(el, true)) {
console.log("100% on screen.");
} else if (v.isElementOnScreen(el)) {
console.log("Some parts are on screen");
} else {
console.log("not on screen at all");
}
```
Use only vertical:
```
var vertical = require('viewability/vertical');
vertical(document.getElementById('blue-box'));
// return {value: 1, state: "EL_IS_WITHIN_VERTICAL_VIEW"}
```
Use only horizontal:
```
var horizontal = require('viewability/horizontal');
vertical(document.getElementById('blue-box'));
// return {value: 1, state: "EL_IS_WITHIN_HORIZONTAL_VIEW"}
```
# Running tests
While `viewability` has no dependencies, testing uses Karma.
```sh
npm install
npm test
```
# License
ISC