Home > Software engineering >  JS - how can i make divs appear like in example?
JS - how can i make divs appear like in example?

Time:01-30

Example

i need to make divs appear like this, or any other fancy way. Can someone provide source or something that can help?

CodePudding user response:

We can add the class name of a CSS attribute with a transition, and animate property to switch it from an opacity: 0 element to an opacity: 1 element, and assign it an animation attribute that slides it in using the CSS transform property.

We can use getBoundingClientRect and scrollTop to check when the element is in view, and add the class when it is.

This gives us something close to the desired effect.

document.addEventListener("scroll", (event) => {
  const elementsToAnimate = Array.from(document.querySelectorAll(".stationary"));

  for (element of elementsToAnimate) {
    const {
      scrollTop
    } = document.querySelector("html");
    const {
      top
    } = element.getBoundingClientRect();

    const containsAnimateClass = element.classList.contains("from-left");

    if (top < scrollTop / 2 && !containsAnimateClass)
      element.classList.add("from-left");
  }
});
body {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.stationary {
  opacity: 0;
  width: 100px;
  height: 100px;
  background: red;
}

.from-left {
  transition: 1s ease;
  opacity: 1;
  animate: 1s ease slide-in-from-left;
}

@keyframes slide-in-from-left {
  from {
    transform: translateX(-50%);
  }
  to {
    transform: translateX(0);
  }
}
<body>
  <div>Scroll!</div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</body>

CodePudding user response:

You can use simple libraries already implemented these animations:

https://github.com/matthieua/WOW

https://scrollrevealjs.org/

https://scrollmagic.io/examples/basic/reveal_on_scroll.html

https://michalsnik.github.io/aos/ (I personally love this, its easy to use)

Or in other hand make your own animation. add event listener for scroll and create a keyframe animation. Then assign the class to the element when scroll reached to your desire number.

CodePudding user response:

yes!its work this libraries are really good

  •  Tags:  
  • Related