Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla JS, Add and Remove on Class on Scroll position

Hey i am trying to add a class depending on the scroll position. It worked in Jquery but i want to move to vanilla, it doesn't work. What am i missing?

IF the User scrolls to position 30px it should add the class .c-logo--scrolled

Console Error:

Uncaught TypeError: Cannot read property 'add' of undefined at add_class_on_scroll (app.min.js:17) at app.min.js:29

var scrollPosition = window.scrollY;
var logoContainer = document.getElementsByClassName('js-logo');

window.addEventListener('scroll', function() {

    scrollPosition = window.scrollY;

    if (scrollPosition >= 30) {
        logoContainer.classList.add('c-logo--scrolled');
    } else {
        logoContainer.classList.remove('c-logo--scrolled');
    }

});
like image 426
HendrikEng Avatar asked Feb 05 '23 11:02

HendrikEng


1 Answers

var logoContainer = document.getElementsByClassName('js-logo');
var logoContainer = document.getElementsByClassName('js-logo')[0];

Then:

  1. Place your scripts in the bottom of the body.
  2. Ensure what element is really scrolling - it's not always window.
  3. https://developer.mozilla.org/ru/docs/Web/API/Window/scrollY - no support in IE
  4. http://caniuse.com/#feat=classlist - partial support in IE10+
like image 134
Qwertiy Avatar answered Feb 08 '23 12:02

Qwertiy