Search code examples
javascripthtmlscrollalways-on-top

Javascript library to do autoscroll of a div fixed to left of page


I want a JS library which can allow me to build an attractive menu which is always visible to the user on the left side of the screen, approx. to the middle.


Solution

  • Since you've asked for a library, here is in jQuery. It uses CSS position: fixed if it's available, and degrades gracefully to the javascript way if needed.

    [See it in action]

    CSS

    #menu { 
      position: absolute; 
      left: 0; 
      top: 50%; 
      /* ... */
    }
    

    Javascript

    (function() {
    
    var $menu   = $("#menu");
    var $window = $(window);
    var menuHalfHeight = $menu.outerHeight() / 2;
    
    var updateMenu = function() {
      $menu.css({
        "margin-top": - menuHalfHeight + $window.scrollTop()
      });   
    };
    
    var supportFixed = (function() {
      $menu.css({ position: "fixed" });
      updateMenu();
      return $menu.offset().top > 0; // ~150
    })();      
    
    if (!supportFixed) {
      $menu.css({ position: "absolute" });
      $window.scroll(updateMenu);
    }
    
    })();