viewport-funcs
A very limited subset of viewport functions I use every day
Install
npm i viewport-funcs
Package on npm
API
contains(el, [offset], [check])
Check if el
is in the viewport, return a boolean
Argument | Action |
---|---|
el | the tested Html Element el |
offset | optional offset , default to 0 |
check | optional check , default to false . If true performs multiple tests explained below |
If check
is true
, safer but slower tests are performed
- check if
el
is a Html Element, with nodeType 1 and landed in the document.body - check if
el
has no size. An empty or adisplay:none
div or an img with no src will always returnfalse
const contains = var el = document // true if the element is fully or partially in the viewport
margins()
Get the viewport size and margins
left
, top
, right
and bottom
are relative to each side of the document
The object returned contains:
Key | Value |
---|---|
width | the viewport width |
height | the viewport height |
left | the margin-left , distance between the left of the document and the left of the viewport |
top | the margin-top , distance between the top of the document and the top of the viewport |
right | the margin-right , distance between the right of the document and the right of the viewport |
bottom | the margin-bottom , distance between the bottom of the document and the bottom of the viewport |
The example below shows:
- how to get the viewport bottom-right corner location
- how to get the document width and height
const margins = // {width: 591, height: 328, left: 0, top: 56, right: 0, bottom: 316}var data = /*the viewport bottom-right corner location{x: 591, y: 384}*/var br = x: dataleft + datawidth y: datatop + dataheight /*the document width and height{width: 591, height: 700}*/var doc = width: dataleft + datawidth + dataright height: datatop + dataheight + databottom
The returned object is internally cached to boost performance
rect()
Get the viewport size and position
left
, top
, right
and bottom
are relative to the top-left of the document
The object returned contains:
Key | Value |
---|---|
width | the viewport width |
height | the viewport height |
left | the distance between the left of the document and the left of the viewport |
top | the distance between the top of the document and the top of the viewport |
right | the distance between the left of the document and the right of the viewport |
bottom | the distance between the top of the document and the bottom of the viewport |
This means:
right
=left
+width
bottom
=top
+height
The returned object is internally cached to boost performance
const rect = // {width: 800, height: 600, left: 10, top: 10, right: 810, bottom: 610}
Thanks
Mainly forked / inspired on
Performance and tips from
License
MIT