1

I've added a floating action button on my site. I really know nothing about JavaScript and jQuery. Can I get a way by which the floating action button disappears when the window is scrolling and appears when window stops scrolling.

hdd
  • 45
  • 7

2 Answers2

1

There's no direct event for scroll stop but there's a work around done here; Event when user stops scrolling

Just added a few tweaks like hiding the button during scroll and showing if it passed a few milliseconds.

$.fn.scrollEnd = function(callback, timeout) {
  $(this).scroll(function() {
    // hide button
    $(".floatingBtn").hide();

    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback, timeout));
  });
};

$(window).scrollEnd(function() {
  // show button if scrolling stopped
  $(".floatingBtn").show();
}, 600);
.container {
  height: 1200px;
}

.floatingBtn {
  position: fixed;
  bottom: 12px;
  right: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <button class="floatingBtn">Hello World!</button>
</div>
Jerdine Sabio
  • 5,688
  • 2
  • 11
  • 23
1

Try the below code. that should work. Replace the id of your element with "YOURID" in the below code.

 $.fn.scrollStopped = function(callback) {
                      var that = this, $this = $(that);
                     $this.scroll(function(ev) {
                       clearTimeout($this.data('scrollTimeout'));
                       $this.data('scrollTimeout', setTimeout(callback.bind(that), 250, ev));
                     });
                   };
            $(window).on("scroll",function(e){ $("#YOURID").hide(); }).scrollStopped(function(ev){ 
                   $("#YOURID").show(); })
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <BODY style="height:1200px;">
        <br><br><br><br><br><br>
        <button id="YOURID" type="buton" style="position:fixed">FLOATING BUTTON</button>
        </BODY>
Maharshi
  • 1,178
  • 1
  • 14
  • 37
  • Thank you so mcuh sir, for helping.This is what i was searching for everywhere. – hdd Dec 19 '19 at 07:28