Slowly hide a banner on scroll down and bring back on scroll to top of page

282 Views Asked by At

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:

  1. animate() with height and opacity - https://jsfiddle.net/kellyking/9ez2sp4r/46/
$(window).scroll(function() {
  if ($(this).scrollTop() > 0) {
    $(".callout-banner").animate({height: "0px",opacity: "0"});
  } else {
   $(".callout-banner").animate({height: "150px",opacity: "1"});
  }
});
  1. fadeIn and fadeOut - https://jsfiddle.net/kellyking/ukgm39o6/133/
$(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.

  1. leaves a large blank spot when it disappears and then it never comes back
  2. works a little better, in that the banner both goes away and comes back, but really is jumpy

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.

1

There are 1 best solutions below

1
Mohamed-Yousef On BEST ANSWER

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>