1

I have a scroll indicator button that translates X off the screen when user scrolls and shows back when user scrolls up. I would like the button to appear / come back when the user stops scrolling, not when they scroll up.

I tried toggling class but it's not behaving correctly.

jQuery:

var prev = 0;
var $window = $(window);

$window.on('scroll', function(){
    var scrollTop = $window.scrollTop();
    scrollButton.toggleClass('hidden', scrollTop > prev);
    prev = scrollTop;
});

CSS:

.hidden {
   transform: translateX(250%);
 }
freginold
  • 3,946
  • 3
  • 13
  • 28
hendy0817
  • 979
  • 2
  • 20
  • 47
  • 1
    Possible duplicate of [How do I know when I've stopped scrolling?](https://stackoverflow.com/questions/4620906/how-do-i-know-when-ive-stopped-scrolling) – Nawed Khan Sep 11 '19 at 15:13

1 Answers1

0

You can achieve that by using a Timeout as a threshold.

For example:

var timer;
$(document).scroll(function(){

  if(timer != "undefined"){
    clearTimeout(timer);
  }
  
  $('p').hide();
  timer = setTimeout(function(){
    
    $('p').show();

  },250)//Threshold is 100ms

});
<style>

body{height:1000px;width:100%;}
div{width:100%;height:150px;overflow:hidden;}
p{background-color:black;color:white;width:100px;margin:50px auto;padding:20px;}  

</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Hide on scroll</p>
</div>

Note: Make sure that the section you want to hide is contained inside a div container with a overflow:hidden; property, Also use a fixed height, because every time that section is toggled the document will scroll automatically which will trigger the event again (debouncing).

I hope this works!

Ahmed Salameh
  • 269
  • 2
  • 11
  • This is also called `debouncing` - in practice you'd probably want a smaller timeout, but shows as an example. – freedomn-m Sep 11 '19 at 15:40