Skip to content

Instantly share code, notes, and snippets.

@musamamasood
Created June 10, 2016 20:02
Show Gist options
  • Save musamamasood/9d200cee89e1cd9c4e9755844d9dcdbe to your computer and use it in GitHub Desktop.
Save musamamasood/9d200cee89e1cd9c4e9755844d9dcdbe to your computer and use it in GitHub Desktop.
Create an animated sticky header with css3 and javascript.
<script>
/**
* Add Class to header area to make it sticky.
* Placed into header or footer area.
*/
function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop,
shrinkOn = 300,
header = document.getElementById("headerID"); //Header ID
if (distanceY > shrinkOn) {
header.classList.add("sticky");
} else {
if (header.classList.contains("sticky")) {
header.classList.remove("sticky");
}
}
});
}
window.onload = init();
</script>
<style>
/*
* Add styling to class
*/
header {
transition: all 0.4s ease;
}
.sticky {
position: fixed !important;
background-color: #000;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment