0

Initially, the child element opacity is set to 0 except for the first child that is already on top, and when the scroll happens the next child to reach the top of the parent container, opacity will be set to 1 and the same thing happens for the rest of the child.

<div class="parent"> // scrollable parent container
  <div class="child">I am child 1</div>  // currently visible child with opacity 1       
  <div class="child">I am child 2</div>  // next child element with opacity 0.5
  <div class="child">I am child 3</div>  // next child element with opacity 0.5
  .....
</div>

I've seen this post Increase element opacity when user scrolls down the page , but this one is jquery. Can't find something similar for pure javascript and also this only contain one child element.

Don't know where to start. Any help is very much appreciated.

fmsthird
  • 1,745
  • 2
  • 17
  • 34

1 Answers1

0

Okay, after several hours of trying / researching. I finally able to solve it. I will post my solution so that it may help others who will have the same use case with me.

const parentContainer = document.getElementById('parent');
parentContainer.addEventListener(
    'scroll',
   event => {
      [].slice.call(event.target.children).map(el => {
          if (el.offsetTop - 100 < event.target.scrollTop) {
            el.style.opacity =
              1 -
              ((el.clientHeight - event.target.scrollTop) /
                el.clientHeight) *
                0.7 +
              0.3;
          } else {
            el.style.opacity = 0.3;
          }
      });
    }
  )   

What I did above is get the parent element and added scroll event listener. Map through its child elements and then get the child offsetTop value and compared it to parent scrollTop value, if it's less than apply the logic I found from the reference link above to increase the opacity else (when scroll up) return to default opacity.

I hope this is clear for anyone looking for the same solution.

fmsthird
  • 1,745
  • 2
  • 17
  • 34