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 7 months 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 7 months 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 7 months ago
awarded to kerncy

Crowdsource coding tasks.

1 Solution


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 ( >= 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) {
      found = true;
    else {
}, 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 in the CSS to have a visual feedback if needed.

EDIT : Direct link to a copy of the pen

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.
imokyourok 7 months ago
I made a fix to handle your requirement, should be better :
kerncy 7 months ago
Away from my computer for a bit. tested it on my phone and it worked. Will update you shortly.
imokyourok 7 months ago
Thank you for the tip !
kerncy 7 months ago