Is there a way to animate an element when it becomes visible on scroll, rather than at a fixed position on the page? I'm currently using code that triggers the animation based on an absolute scroll position, but I'm looking for a more dynamic solution.
I've been using the SlideUp animation, but I'm unsure of how to write the code to reveal the element on scroll. Can someone provide guidance or a small example of how to achieve this?
Here is the current code:
function reveal() {
if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
document.getElementById("myDiv").className = "slideUp";
}
}
/* When Class changed to slideUp, Animation will start */
.slideUp {
animation-name: slideUp;
-webkit-animation-name: slideUp;
animation-duration: 1s;
-webkit-animation-duration: 1s;
visibility: visible;
}
@keyframes slideUp {
0% {
opacity: 0;
-webkit-transform: translateY(70%);
}
100% {
opacity: 1;
-webkit-transform: translateY(0%);
}
}
@-webkit-keyframes slideUp {
0% {
opacity: 0;
-webkit-transform: translateY(70%);
}
100% {
opacity: 1;
-webkit-transform: translateY(0%);
}
}
<!-- Div has absolutely positioned to avoid showing when page load first time|Because, User should scroll to it for animate it. -->
<div id="myDiv" style="position:absolute;top:1500px;left:1px;">
<p>Example text</p>
</div>