Using inViewport
The following are two examples of how to apply inviewport to an element. Feel free to hop on over to the inViewport github page for more information.
/**
* Toggle example.
* The threshold is set to one in this example so once the element
* is fully visible the first callback is fired. The second callback
* is then fired if the element is no longer fully visible.
*/
const selectorA = document.getElementById('selector-a');
inViewport(selectorA, 1,
[
() => {
selectorA.classList.add('visible');
console.log('The element is now visible!');
},
() => {
selectorA.classList.remove('visible');
console.log('The element is now hidden.')
},
]
);
/**
* Static example.
* The threshold in this example is set to 0.5 so once the element
* is 50% visible, the callback is fired.
*/
const selectorB = document.getElementById('selector-b');
inViewport(selectorB, 0.5, () => {
selectorB.classList.add('visible');
console.log('The element is now visible!');
});
Scroll down to test.
Toggle Example
Scroll right to test.
Static example