14. Dezember 2023
Text-Fade-in-Effekt mit CSS und JavaScript
Mit folgendem Snippet lässt sich ein subtiler, schicker Text-Eingangs-Effekt erzielen, der sich insbesondere für große Headlines eignet.
Lorem ipsum
dolor sit amet
constructor
<div class="scrolldetected appear">
<div><h1>Lorem ipsum</h1></div>
</div>
<div class="scrolldetected appear">
<div><h1>dolor sit amet</h1></div>
</div>
<div class="scrolldetected appear">
<div><h1><b>constructor</b></h1></div>
</div>
<style>
.appear h1 {
font-weight: 600;
font-size: clamp(20px, 8.0vw, 60px);
line-height: 0.8;
color:#111;
transition: 1.3s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.appear{
overflow: hidden;
}
.appear div{
transform: translate(0,140%);
transition: 1.3s cubic-bezier(0.075, 0.82, 0.165, 1);
opacity: 1;
}
.appear.active div{
transform: translate(0,0%);
opacity: 1;
}
</style>
<script type="text/javascript">
const elements = document.querySelectorAll(".scrolldetected");
function checkElements() {
const scrolldetectedElements = document.querySelectorAll(".scrolldetected");
if (scrolldetectedElements.length > 0) {
activateElements(scrolldetectedElements, 150);
}
}
function activateElements(elements, delay) {
elements.forEach((element, index) => {
setTimeout(() => {
if (isElementInViewport(element)) {
element.classList.add("active");
}
}, index * delay);
});
}
function isElementInViewport(element) {
var rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth) &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)
);
}
window.addEventListener("load", checkElements);
window.addEventListener("scroll", checkElements);
</script>
Code-Sprache: HTML, XML (xml)