Reputation: 635
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?
Upvotes: 5
Views: 5420
Reputation: 16170
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:
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
Upvotes: 6
Reputation: 1237
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
}
Upvotes: 1
Reputation: 114
You can use Waypoints.js to set what happens when you reach a specific element of a page.
Upvotes: 0
Reputation: 9329
With pure CSS: no.
But you can have a class with keyframed animation associated with it, and then say when the element is scrolled into view, to add the class to the element. This will make it start doing the animation.
Upvotes: 0
Reputation: 167182
Scrolling is an event. Once you scroll the page, the event gets triggered and something happens. You cannot control events using Pure CSS. Period.
Some people would argue that even :hover
is an event. Yes, and it is for some strange reason, implemented in CSS, but not others.
Upvotes: 0