Can't Add Classes With intersectionObserver JavaScript API

35 Views Asked by At

I once tried to follow a tutorial from FireShip about Scroll Animations. I followed everything that is in the video, but somehow can't get the JavaScript code to work. When I run it, it's just a black screen without the h1 elements slowly showing up by decreasing the opacity I then figured out that my JavaScript can't add classes to my h1 elements using classList.add() when my viewport is intersecting with the element.

Here is the HTML, CSS and JavaScript used:

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add('show');
    } else {
      entry.target.classList.remove('show');
    }
  });
});

const hiddenElements = document.querySelectorAll('.hide');

hiddenElements.forEach((el) => observer.observe(el));
* {
  font-family: "Roboto", sans-serif;
  background-color: black;
}
section {
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  min-height: 100vh;
  font-size: 3em;
}

.hide {
  opacity: 0;
  transition: all 1s;
}

.show {
  opacity: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cool Scrolls</title>
  <link rel="stylesheet" href="style.css">
  <script differ src="script.js"></script>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
</head>
<body>
  <section>
    <h1 class="hide">Introducing</h1>
  </section>
  <section>
    <h1 class="hide">The One And Only</h1>
  </section>
  <section>
    <h1 class="hide">"Hello World"</h1>
  </section>
</body>
</html>

Is there something wrong with them?

0

There are 0 best solutions below