How to add a CSS class on scroll

To add a CSS class on scroll, you can use JavaScript to listen for the scroll event and manipulate the class of the desired element. Here’s an example of how you can achieve this:

HTML:

<!DOCTYPE html>
<html>
<head>
  <style>
    .myClass {
      /* Define the styles for the class */
      background-color: red;
      /* Add more styles as needed */
    }
  </style>
</head>
<body>
  <div id="myElement">Scroll down to see the class added</div>

  <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

window.addEventListener('scroll', function() {
  var element = document.getElementById('myElement');
  var scrollPosition = window.scrollY;

  if (scrollPosition > 200) {
    // Add the class if the scroll position is greater than 200px
    element.classList.add('myClass');
  } else {
    // Remove the class if the scroll position is less than or equal to 200px
    element.classList.remove('myClass');
  }
});

In the above example, when the user scrolls down and the scroll position exceeds 200 pixels, the CSS class «myClass» will be added to the element with the ID «myElement». If the scroll position is less than or equal to 200 pixels, the class will be removed.

You can adjust the scroll position threshold and customize the CSS class and styles to fit your specific needs.