Last active
December 21, 2020 12:10
-
-
Save PechenkiUA/5ebeb1856d9d499319ef0b32112ff648 to your computer and use it in GitHub Desktop.
Position Fixed header to scroll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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