Skip to content

Instantly share code, notes, and snippets.

@PechenkiUA
Last active December 21, 2020 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PechenkiUA/5ebeb1856d9d499319ef0b32112ff648 to your computer and use it in GitHub Desktop.
Save PechenkiUA/5ebeb1856d9d499319ef0b32112ff648 to your computer and use it in GitHub Desktop.
Position Fixed header to scroll
<script>
fixedHeader = () => {
this.fix = () => {
if (window.innerWidth < 768) {
window.onscroll = function () {
myFunction()
};
var header = document.querySelector(".header");
var sticky = header.offsetTop;
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
document.querySelector('body').classList.add("sticky")
document.body.style.marginTop = header.offsetHeight + 'px'
} else {
header.classList.remove("sticky");
document.querySelector('body').classList.remove("sticky")
document.body.style.marginTop = '';
}
}
}
}
this.fix()
}
fixedHeader()
</script>
<style>
.header.sticky {
position: fixed;
top: 0;
width:100%;
z-index: 9999;
background: #f0f0f0;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment