I'm trying to slowly hide a banner (within a fixed element) on scroll down, and then when the user scrolls back to the top of the page, bring the banner back. I'm using jQuery.
I've tried using:
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
$(".callout-banner").animate({height: "0px",opacity: "0"});
} else {
$(".callout-banner").animate({height: "150px",opacity: "1"});
}
});
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
$('.callout-banner').fadeOut( "slow" );
} else {
$('.callout-banner').fadeIn( "slow" );
}
});
They both sort of work but both have problems.
I've read A LOT of other posts, and then don't seem to work in this situation when the banner is inside a fixed element, and I only want it to come back when the user scrolls all the way back to the top of page.
Use boolean to stop repeating the animation
let scrolling = true;
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
if(scrolling === true){
$(".callout-banner").animate({height: "0px",opacity: "0"});
scrolling = false;
}
} else {
if(scrolling === false){
$(".callout-banner").animate({height: "150px",opacity: "1"});
scrolling = true;
}
}
});
div.content {
border: 1px solid black;
padding: 3rem;
}
.header {
position: fixed;
top:0;
background-color: grey;
padding:0 0 2rem 0;
width:100%;
}
.callout-banner {
background-color: yellow;
padding: 1rem;
}
.header-content {
padding:1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
<section class="custom-components callout-banner"><a href="#">this is the link</a></section>
<div class="header-content">
this is more header content
</div>
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>
<div class="content">
more content
</div>