I am looking for a way to animate (with @keyframes
, transform
...) some elements when the user scrolls the page. For example:
div
has height: 100px
.div
is height: 50px
and color: blue
.Is is possible using pure CSS? If it is not, what are the most efficient ways to do it with HTML or Javascript?
The most efficient way to animate an element's style properties depending on scroll position will probably be to add a class with a scroll function:
Working Example
myID = document.getElementById("myID");
var myScrollFunc = function() {
var y = window.scrollY;
if (y > 500) {
// myID.style.backgroundColor = "blue"; // you can add individual styles
myID.className = "blue" // or add classes
} else {
// myID.style.backgroundColor = "red";
myID.className = "red"
}
};
window.addEventListener("scroll", myScrollFunc);
body {
height: 1100px;
}
#myID {
position: fixed;
height: 100px;
line-height: 20px;
transition: all 1s;
}
.blue {
background: blue;
animation: myAnimation 1s both;
}
.red {
background: red;
}
@keyframes myAnimation {
0% {
border-radius: 0px;
line-height: 10px;
}
100% {
border-radius: 100%;
line-height: 100px;
}
}
<div id="myID" class="red">Hello world</div>
Docs:
.scrollY
.className
.addEventListener
Methinnks it's not possible to 'spy' scroll with pure css. If you want, you can do this with jQuery:
$(document).scroll(function() {
var pos = parseInt($(document).scrollTop())
if(pos == 0) {
$('.yourDivClass').css({
height : '100px' ,
color : '#fff'
})
}
if (pos > 0 && pos <= 100) {
$('.yourDivClass').css({
height : '50px' ,
color : 'blue'
})
}
console.log(pos)
})
and of course if you wanna get a smooth transition, you supposed to declare transitions in your css file
.yourDivClass {
transition: height 0.5s ease
}
You can use Waypoints.js to set what happens when you reach a specific element of a page.
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