skip to Main Content

I’m just not sure how to call a function when I scroll to a specific section on my page.

EXAMPLE:
I want to change the color of a text when I scroll to the article section.
or… I want to hide a button when I scroll on the last sections of the page.
or… I want to change the background of the page when I scroll to the footer.

I tried something like:

function func() {
var paragraph = document.getElementById('p');
paragraph.style.color = 'red';
};
<section>
<p id="p" onload="func()">
Test
</p>
</section>

2

Answers


  1. You have to use intersection observer

    https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver

    const observedElement = document.querySelector(".section-5");
    
    const intersectionObserver = new IntersectionObserver((entries) => {
      if (entries[0].intersectionRatio > 0) {
        console.log("visible");
        
        // if you want to execute once
        // remove the observer to avoid performance issues
        // intersectionObserver.unobserve(observedElement);
        // intersectionObserver.disconnect();
      }
    });
    
    intersectionObserver.observe(observedElement);
    .section {
      height: 400px;
      border: 1px solid black;
    }
    <div class="section section-1">
      section 1 (scroll down)
    </div>
    <div class="section section-2">
      section 2
    </div>
    <div class="section section-3">
      section 3
    </div>
    <div class="section section-4">
      section 4
    </div>
    <div class="section section-5">
      section 5 (log to console)
    </div>
    <div class="section section-6">
      section 6
    </div>
    Login or Signup to reply.
  2. This function return true if the element is visible and false if not.

    function isInViewport(element) {
        // Get the bounding client rectangle position in the viewport
        var bounding = element.getBoundingClientRect();
    
        // the code checks if it's *fully* visible
        if (
            bounding.top >= 0 &&
            bounding.left >= 0 &&
            bounding.right <= (window.innerWidth || 
            document.documentElement.clientWidth) &&
            bounding.bottom <= (window.innerHeight || 
            document.documentElement.clientHeight)
        ) {
            return true;
        } else {
            return false;
        }
    }
    

    You can add a scrolling event Listener and check if the targeted element is visible.

    this is a demo code you just have to change the variables to use it

     targetElement = document.getElementById('element')
     targetElement.addEventListener('', () => {
          if (isInViewport(targetElement)) {
              // the code that you want to execute
              console.log("visible")
          }
     })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search