Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

82
Views
Increase opacity of child elements when it reaches the top edge of the parent container on scroll

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.

7 months ago · Juan Pablo Isaza
1 answers
Answer question

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.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.