G
G
georgi19842021-06-08 14:53:11
JavaScript
georgi1984, 2021-06-08 14:53:11

How to make js add a class at a certain page scroll and remove it?

Hello, I need to do this:

If the window.pageYOffset scrolling is not equal to 0, i.e. the beginning,
then I need to add the .active class to the tag with the .navbar class.

And if the scroll returned back to its beginning (0), then you need to remove the .active class.
And it should work without reloading the page.

I did only with the if statement, it didn't work for me, nothing works at all

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2021-06-08
@delphinpro

const navbar = document.querySelector('.navbar');

window.addEventListener('scroll', function(){
  navbar.classList.toggle('active', pageYOffset > 0);
});

https://learn.javascript.ru/onscroll

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question