Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery setInterval or scroll

I am working on a project where i need to listen to the scroll event.. i wonder what is a better approach..

1st Approach

 function scroll() {
    if ($(window).scrollTop() > 200) {
        top.fadeIn();
    } else {
        top.fadeOut();
    }
    if (menuVisible) {
      quickHideMenu();
    }
}

2nd Approach

      function scroll() {
          didScroll = true;
      }

      setInterval(function() {
          if ( didScroll ) {
              didScroll = false;
              if ($(window).scrollTop() > 200) {
                  top.fadeIn();
              } else {
                  top.fadeOut();
              }
              if (menuVisible) {
                quickHideMenu();
              }
          }
      }, 250);

Thanks :)

like image 331
Lucky Soni Avatar asked Mar 23 '13 19:03

Lucky Soni


1 Answers

Neither. I was just reading about JS/jQuery patterns. There is an example for the Window Scroll event: jQuery Window Scroll Pattern

var scrollTimeout;  // global for any pending scrollTimeout

$(window).scroll(function () {
    if (scrollTimeout) {
        // clear the timeout, if one is pending
        clearTimeout(scrollTimeout);
        scrollTimeout = null;
    }
    scrollTimeout = setTimeout(scrollHandler, 250);
});

scrollHandler = function () {
    // Check your page position
    if ($(window).scrollTop() > 200) {
        top.fadeIn();
    } else {
        top.fadeOut();
    }
    if (menuVisible) {
        quickHideMenu();
    }
};

Originally from here: Javascript Patterns

like image 128
davebobak Avatar answered Oct 20 '22 20:10

davebobak