How is an HTML element animated as soon as it appears on screen?
I found an example on the stack overflow tour page, where info elements slide into the page as soon as you scroll down far enough. What is the trick behind that?
Can I trigger CSS animations on scroll without Javascript? The short answer is NO. Window scrolling is an event and CSS itself is not capable of detecting event changes as of now. So we must use javascript to measure the scroll and trigger something to which CSS can react.
You need to use JavaScript to detect the location of the viewport and activate it when it becomes visible.
You can use JavaScript to detect and execute the transition and then CSS or JavaScript to do the animations.
There are many jquery based scripts available to accomplish this. Here is one example:
1. Create a Html element you want to check if it's in the viewport.
<div class="demo"></div>
2. Load the jQuery javascript library and jQuery Viewport Checker plugin at the end of your document.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="viewportchecker.js"></script>
3. Call the plugin on this element and do something in the javascript.
<script>
$(document).ready(function(){
$('.demo').viewportChecker({
// Class to add to the elements when they are visible
classToAdd: 'visible',
// The offset of the elements (let them appear earlier or later)
offset: 100,
// Add the possibility to remove the class if the elements are not visible
repeat: false,
// Callback to do after a class was added to an element. Action will return "add" or "remove", depending if the class was added or removed
callbackFunction: function(elem, action){}
});
});
</script>
You can use the intersection Observer for this. 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.
const startAnimation = (entries, observer) => {
entries.forEach(entry => {
entry.target.classList.toggle("slide-in-from-right", entry.isIntersecting);
});
};
const observer = new IntersectionObserver(startAnimation);
const options = { root: null, rootMargin: '0px', threshold: 1 };
const elements = document.querySelectorAll('.card');
elements.forEach(el => {
observer.observe(el, options);
});
.card {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.slide-in-from-right {
animation: 1.5s ease-out 0s 1 slideInFromRight forwards;
}
@keyframes slideInFromRight {
0% {
transform: translateX(50%);
}
100% {
transform: translateX(0);
}
}
<div class="card">
<h2>Card one</h2>
</div>
<div class="card">
<h2>Card two</h2>
</div>
<div class="card">
<h2>Card three</h2>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With