Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate sections in pure CSS when scrolling the page?

Tags:

html

css

I am looking for a way to animate (with @keyframes, transform...) some elements when the user scrolls the page. For example:

  • When offset is 0: div has height: 100px.
  • When offset is between 0 and 100: div is height: 50px and color: blue.
  • And so on...

Is is possible using pure CSS? If it is not, what are the most efficient ways to do it with HTML or Javascript?

like image 564
David Tabernero M. Avatar asked Aug 25 '15 15:08

David Tabernero M.


3 Answers

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

like image 103
apaul Avatar answered Sep 25 '22 04:09

apaul


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
}
like image 31
Dariusz Majchrzak Avatar answered Sep 21 '22 04:09

Dariusz Majchrzak


You can use Waypoints.js to set what happens when you reach a specific element of a page.

like image 26
Dietrich George Avatar answered Sep 24 '22 04:09

Dietrich George