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;
 });

Answers:

Answer

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');
} 
Answer

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;
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.