samedi 30 octobre 2021

add class to element in viewport

I have five sections on my page, and I am trying to add class "active" to the section in the view port. I tried this code but it is not working properly. the code saves all elements with tag name "section" in a node list then created an array of this list, I looped over the array and added an event listener for each element, then I tested if the element is in the viewport is so I add the class else I remove the class. the problem is once the page is scrolled all the five sections will have the class "active" which means that multiple elements have the class "active" at the same time even though only one section is viewed in the port and when I keep on scrolling down the sections that are moved upward out of the viewport have their class "active" removed. how can i have one element with the class "active"image of code at a time?

//values of viewport
const viewWidth = document.documentElement.clientWidth;
const viewHeight = document.documentElement.clientHeight;

//set class active to section in viewport
function sectionInView(x) {
    for (let i = 0; i in x; i++) {
        document.addEventListener("scroll", function () {
            let el = x[i].getBoundingClientRect();
            if (el.top >= 0 && el.left >= 0 && el.bottom <= viewHeight && el.right <= viewWidth) {
                x[i].setAttribute("class", "active your-active-class");

            }
            else {

                x[i].removeAttribute("class", "active your-active-class");
            }
        });
    }
}
sectionInView(sectionListArray);



Aucun commentaire:

Enregistrer un commentaire