Skip to content

Instantly share code, notes, and snippets.

@marcveens
Created March 21, 2017 15:36
Show Gist options
  • Select an option

  • Save marcveens/e35fcde02920e3c45713ca33e1a433f4 to your computer and use it in GitHub Desktop.

Select an option

Save marcveens/e35fcde02920e3c45713ca33e1a433f4 to your computer and use it in GitHub Desktop.
requestAnimationFrame example
<!DOCTYPE>
<html>
<head>
<style>
body {
height: 4000px;
}
.fixed {
position: fixed;
top: 0;
left: 0;
padding: 10px;
background-color: #d8d8d8;
}
</style>
</head>
<body>
<div class="fixed">Current top position: <span class="js-position"></span></div>
<script>
(function () {
var requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function (callback) { window.setTimeout(callback, 1000 / 60); };
function setPosition() {
var position = window.pageYOffset || document.documentElement.scrollTop;
document.querySelector('.js-position').innerHTML = position + 'px';
}
window.addEventListener('scroll', function() {
requestAnimationFrame(setPosition);
});
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment