Is there a way to toggle the visibility of a div based on scrolling? When reaching section 2; The 'banner' div should appear at the start of section 2 and disappear when section 2 ends. But how can I determine when section 2 is finished in this case? It needs to stay fixed under the menubar.
This is not the actual source, but similar scripts and CSS settings. Since the real page is too large to include here.
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var showbar = $('#sec2').height();
var showbar = showbar -25;
if ( scrollTop > showbar) {
$("#banner").fadeIn(700);
}else{
$("#banner").fadeOut(250);
}
});
html, body {
margin:0px;
height:100%;
width:100%;
padding:0;
scroll-behavior: smooth;
}
.container {
position: absolute;
width:100%;
min-height:100%;
height:100%;
text-align: center;
}
.wrapper{
position: relative;
width:100%;
max-width:1000px;
height:100%;
}
section {
display: block;
color:white;
height:100%;
}
#menubar{
position: -webkit-sticky;
position: sticky;
top:0px;
width:100%;
background-color:black;
height:25px;
text-align: center;
z-index:1000;
}
#menubar a {
margin:20px 20px 20px 20px;
text-decoration:none;
color:white;
font-weight:bold;
}
#menubar a:hover {
color:yellow;
}
#sec1 {
background-color:red;
}
#sec2 {
background-color:blue;
}
#sec3 {
background-color:green;
}
#banner {
display:none;
z-index:1000;
position: -webkit-sticky; /* Safari */
position: sticky;
top: 25;
height:35px;
color:black;
background-color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="wrapper">
<div id="menubar">
<a href="#sec1">Section 1</a>
<a href="#sec2">Section 2</a>
<a href="#sec3">Section 3</a>
</div>
<div id="banner">Show this div only in section 2</div>
<section id="sec1"> bla </section>
<section id="sec2"> bla bla </section>
<section id="sec3"> bla bla bla </section>
</div>
</div>
<script>
function scrolled(o){
//visible height + pixel scrolled = total height
if(o.offsetHeight + o.scrollTop == o.scrollHeight){
var x = document.getElementById("#banner");
x.style.display = "block";
} else {
x.style.display = "none";
}}
</script>
I'm hoping someone can provide some guidance.