Home > Net >  How to detect when the user has scrolled to a certain area on the page using JavaScript? and then ru
How to detect when the user has scrolled to a certain area on the page using JavaScript? and then ru

Time:02-11

How to detect when the user has scrolled to a certain area on the page using JavaScript? and then run an animation? I need to run animation when scrolled to that section please help if you know any part of the problem.

CodePudding user response:

u probably want to take a look on the Intersection Observer API which provides just that ability.

from Intersection Observer MDN documentation -

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

for more information checkout mdn's page regarding intersection observer API - https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

CodePudding user response:

You are looking for IntersectionObserver:

const observer = new IntersectionObserver((nodes)=>{
    nodes.forEach(node =>
      node.target.classList.toggle('visible', node.isIntersecting)
    )
});

observer.observe(document.querySelector('.node'))
.node {
  width: 40px;
  height: 40px;
  background: red;
  margin: 500px;
  transition: 1s;
  display: flex;
  justify-content: center;
  align-items: center;
}

.node.visible {
  background: lightgreen;
  border-radius: 50%;
  color: white;
}
<div class='node'>x</div>

CodePudding user response:

If it doesn't have to be in Vanilla Javascript You could look at this library https://greensock.com/scrolltrigger/

  • Related