How to play an animation (change element class) on most html elements as they scroll into view?

yotube
0

Issue

I am very new to javascript and am trying to add an animation to most of the elements on my webpage, when they come into view. I am using the method shown here. What it does is add a class to the element when the element enters the viewport, and the animation is played in css on all elements with that class. When the element leaves the viewport, it removes the class. The original code was supposed to work for just one element, but I want to do it for everything inside a div with the class content. As I said, I really don't know javascript very well, so the only thing I could think of was to make a list of all the elements in that div, and then have the code for watching, and then adding or removing the classes, run on each of those elements. This method not only errored, but I am sure there must be a better ways to do this.

My javascript:

const observer = new IntersectionObserver(entries => {
// Loop over the entries
entries.forEach(entry => {
// If the element is visible
if (entry.isIntersecting) {
// Add the animation class
entry.target.classList.add('object-animation1');
} else { //If not visible
//Remove the animation class
entry.target.classList.remove('object-animation1');
}

});
});


content = document.querySelector('.content');
elements = content.getElementsByTagName("*");

console.log(elements);

elements.forEach(current => {
observer.observe(current);
});

The error:

Home-JS.js:22 > Uncaught TypeError: elements.forEach is not a function
at Home-JS.js:22

Example HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<!-- all that stuff here>
</head>
<body>
<div class="navbar">
<!-- Navbar stuff>
</div>
<div class="header">
<!--header stuff>
</div>
<div class="content">
<!--This is what I want to be animated>
</div>
<script src="Home-JS.js"></script>
</body>
</html>

Sorry that I have barely any idea what I am talking about here, any help is appreciated!


Solution

Queries for DOM elements like querySelector, getElementsByTagName returns a collection of DOM elements not an array this is the problem that you are facing. Try to iterate this collection with a for of loop instead forEach Array function.

const HTMLDOMLList = document.getElementsByTagName("a")
for (let item of HTMLDOMlist) {
// your code
console.log(item.href)
}


Answered By - David

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top