I have a <header>
that in turn contains two divs, as shown in the following image:
In the upper half the div A and in the lower half the div B. Well, what I want to do is a sticky menu, that when the upper part of the lower div (red) is zero then the whole header has a fixed position, hiding the upper div (blue) with the browser window. That is:
This is my code:
$(document).ready(function(){
let smenu = $('.divB');
stickyMenu(smenu);
function stickyMenu(menu){
$(window).on('scroll', function(){
if($(this).scrollTop() > menu.offset().top) menu.addClass('menu-fixed');
else menu.removeClass('menu-fixed');
});
}
});
body {
height: 8000px;
}
header{
background-color: transparent;
width: 95%;
margin: auto;
overflow: hidden;
transform: translateY(20px);
}
header .divA{
width: 100%;
background-color: #FFF;
z-index: 1;
overflow: hidden;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
height: 40px;
width: 100%;
background-color: red;
}
header .divB{
width: 100%;
background-color: #FFF;
z-index: 1;
overflow: hidden;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
height: 40px;
width: 100%;
background-color: green;
}
/*This class is to "stick" the menu on the top*/
.menu-fixed{
position: fixed;
z-index: 999;
width: 100%;
top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
<div class="divA">
divA
</div>
<div class="divB">
divB
</div>
</header>
The problem is that when doing scroll, the complete header leaves the window (upwards) and gets stuck there until I scroll down.