Add/Remove class based on scroll and position
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need to have a class added and removed from an element based on scroll position. In the attached CodePen and videos the H2 element needs to have a class added and removed as the user scrolls the site so only one H2 element has the added class at anyone time. The solution, either needs to be vanilla JavaScript or pure CSS (if possible) and responsive. Solutions can't be based on the browser window's pixel dimensions.

CodePen non Working Example

Video Example One

Video Example Two

I have a misunderstanding. The class that needs to be set/add, it's the green effect on the videos ?
kerncy 14 days ago
Yes, I need to add/remove a class that would allow me to change the CSS of an element. In the video I'm trying to demonstrate adding a class on scroll that would allow me to change the color of the H2 element's text (green).
imokyourok 14 days ago
I’m away from my computer for a little bit, so I can’t fully test right now. It does work on my phone. I’ll get back to you as soon as I can.
imokyourok 14 days ago
awarded to kerncy

Crowdsource coding tasks.

1 Solution

Winning solution
Tipped

Hi

I have issues with codepen to save the document and have a direct link, but you can try to add the following code to your JS part :

var isInViewport = function (elem) {
    var bounding = elem.getBoundingClientRect();
    return (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
};

window.addEventListener('scroll', function (event) {
  var titles = document.querySelectorAll('h2');
  var found = false;
  for (var i = 0; i < titles.length; i++) {
      if (isInViewport(titles[i]) && !found) {
          titles[i].classList.add("active");
      found = true;
      }
    else {
      titles[i].classList.remove("active");
    }
  }
}, false);

It will test if h2 element are in viewport and set the "active" class to the first visible of the list. You can add "color: #00ff00;" to your h2.active in the CSS to have a visual feedback if needed.

EDIT : Direct link to a copy of the pen https://codepen.io/kerncy-the-scripter/pen/VwwRRor

It's not working like it does in my video example. The classes needs to be added to the H2 element as it comes into the screen from the bottom, and removed from the H2 element(s) above it. https://codepen.io/browsersdevicesfonts/pen/4ed98900863b2c5aacdc9b077332cf95
imokyourok 14 days ago
I made a fix to handle your requirement, should be better : https://codepen.io/kerncy-the-scripter/pen/VwwRRor
kerncy 14 days ago
Away from my computer for a bit. tested it on my phone and it worked. Will update you shortly.
imokyourok 14 days ago
Thank you for the tip !
kerncy 14 days ago