add class when element in viewport vanilla javascript

Solutions on MaxInterview for add class when element in viewport vanilla javascript by the best coders in the world

showing results for - "add class when element in viewport vanilla javascript"
Lennart
13 Mar 2019
1window.addEventListener('scroll', function (event) {
2    if (isInViewport(theElementToWatch)) {
3      // update the element display
4    }
5}, false);
6
Luca
24 Nov 2016
1function isInViewPort(element) {
2    // Get the bounding client rectangle position in the viewport
3    var bounding = element.getBoundingClientRect();
4
5    // Checking part. Here the code checks if it's *fully* visible
6    // Edit this part if you just want a partial visibility
7    if (
8        bounding.top >= 0 &&
9        bounding.left >= 0 &&
10        bounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
11        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
12    ) {
13        console.log('In the viewport! :)');
14        return true;
15    } else {
16        console.log('Not in the viewport. :(');
17        return false;
18    }
19}
20