Sidarth Roy
Sidarth Roy

Reputation: 1

How to detect when the user has scrolled to a certain area on the page using JavaScript? and then run an animation?

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.

Upvotes: 0

Views: 518

Answers (3)

Michaela
Michaela

Reputation: 339

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

Upvotes: 0

stacj
stacj

Reputation: 1121

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>

Upvotes: 1

gil
gil

Reputation: 2552

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

Upvotes: 0

Related Questions