My issue is in the
script
body
pageTop
menu
yPos
yScroll
function
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0px;
text-align: center;
}
#pagetop {
position: fixed;
top: 0px;
width: 100%;
height: 120px;
background: #06C;
color: #FFF;
font-size: 23px;
padding-top: 50px;
transition: height 0.3s linear 0s, padding 0.3s linear 0s;
overflow: hidden;
}
#pagetop > #menu {
position: absolute;
bottom: 0px;
width: 100%;
background: #004A95;
height: 50px;
transition: height 0.3s linear 0s;
}
#wrapper {
margin-top: 230px;
}
</style>
</head>
<body>
<div id="pagetop">
Header
<div id="menu">Menu system</div>
</div>
<div id="wrapper">
<script>
for(i = 0; i < 40; i++)
{
document.write("<h2>dummy page content</h2>")
}
</script>
</div>
<script>
var pagetop = document.getElementById('pagetop');
var menu = document.getElementById('menu');
var yPos = window.pageYOffset;
window.addEventListener('scroll', yScroll);
function yScroll() {
if (yPos > 150) {
pagetop.style.height = '36px';
pagetop.style.paddingTop = '8px';
menu.style.height = '0px';
}
else {
pagetop.style.height = '120px';
pagetop.style.paddingTop = '50px';
menu.style.height = '50px';
}
}
</script>
</body>
</html>
Your code is working fine, except that yPos
is only set once at page load and will always stay 0
.
To resolve this, read the scroll position each time the event handler is called, inside your yScroll
function:
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0px;
text-align: center;
}
#pagetop {
position: fixed;
top: 0px;
width: 100%;
height: 120px;
background: #06C;
color: #FFF;
font-size: 23px;
padding-top: 50px;
transition: height 0.3s linear 0s, padding 0.3s linear 0s;
overflow: hidden;
}
#pagetop > #menu {
position: absolute;
bottom: 0px;
width: 100%;
background: #004A95;
height: 50px;
transition: height 0.3s linear 0s;
}
#wrapper {
margin-top: 230px;
}
</style>
</head>
<body>
<div id="pagetop">
Header
<div id="menu">Menu system</div>
</div>
<div id="wrapper">
<script>
for (i = 0; i < 40; i++) {
document.write("<h2>dummy page content</h2>")
}
</script>
</div>
<script>
var pagetop = document.getElementById('pagetop');
var menu = document.getElementById('menu');
window.addEventListener('scroll', yScroll);
function yScroll() {
var yPos = window.pageYOffset;
if (yPos > 150) {
pagetop.style.height = '36px';
pagetop.style.paddingTop = '8px';
menu.style.height = '0px';
} else {
pagetop.style.height = '120px';
pagetop.style.paddingTop = '50px';
menu.style.height = '50px';
}
}
</script>
</body>
</html>