Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery scroll event

I am trying the following jQuery code.
When I scroll either up or down I want to fadeOut a div and when the scroll has stopped fadeIn the same div.

What I have is this:

$(document).ready(function(){
   $(window).scroll(function(e){
     $('#search_tab').fadeOut('slow'); 
   }); 
});

I know that this will fadeOut the div when the scroll has started, but the trick is to fade it back once I stop scrolling.

Now, I have seen this(but still not quite what I want)

    //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

The above function will not work at all as follows:

 $(window).bind('DOMMouseScroll', function(e){
     if(e.detail > 0) {
         //scroll down
         $('#search_tab').fadeOut('slow');
     }else {
         //scroll up
         $('#search_tab').fadeOut('slow');
     }

     //prevent page fom scrolling
     return false;
 });
like image 641
user1965451 Avatar asked Jan 10 '13 04:01

user1965451


2 Answers

There isn't a scrollstop listening event but you can emulate one by using a setTimeout() function and then clearing the timer every time the page scrolls. Here is a sample fiddle.

var timer;     
$(window).scroll(function(e){
         clearTimeout(timer);
         $('#search_tab').fadeOut('slow');
         timer = setTimeout(checkStop,150);
 });

function checkStop(){
  $('#search_tab').fadeIn('slow');
} 
like image 194
Blake Plumb Avatar answered Sep 19 '22 16:09

Blake Plumb


You can check on every frame:

// shim for frame listener
window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function( callback ){
                window.setTimeout(callback, 1000 / 60);
              };
    })();

    // on every frame, call render()
    (function animloop(){
      requestAnimFrame(animloop);
      render();
    })();


var lastScroll = 0, isScrolling = false;
function render(){
  var thisScroll = $(window).scrollTop();
  if(lastScroll !== thisScroll){
     if(!isScrolling){
        // scrolling has started, fade out div
        $('#search_tab').stop().fadeOut('slow'); 
     }
     isScrolling = true;
   }else{
     if(isScrolling){
       // scrolling has stopped, fade in div
       $('#search_tab').stop().fadeIn('slow'); 
     }
     isScrolling = false;
  }
  lastScroll = thisScroll;
}
like image 37
Nick Jonas Avatar answered Sep 18 '22 16:09

Nick Jonas