Snippets

Willy Bahuaud Sidebar fixe

Created by Willy Bahuaud

File script.js Added

  • Ignore whitespace
  • Hide word diff
+jQuery(document).ready(function($){
+    var $sidebar = $('.sidebar:eq(0)');
+    var sidebarPos = false;
+    function resizeScreen() {
+        if ( $sidebar.length ) {
+            sidebarPos = {
+                top:$sidebar.offset().top - 60,
+                bottom:$sidebar.offset().top + $sidebar.find('.sidebar-content').height() - $(window).height() + 20,
+                width:$sidebar.width(),
+                footer:$('#footer').offset().top - $(window).height(),
+            }
+            $('.sidebar-content').css('width',$sidebar.width());
+        }
+    }
+    $(window).on('resize',resizeScreen);
+    resizeScreen();
+
+    var scrollPos;
+    function scrollScreen() {
+        if ( sidebarPos ) {
+            scrollPos = $(window).scrollTop();
+            if ( scrollPos > sidebarPos.top ) {
+                $sidebar.addClass('fixed-for-top');
+                if ( scrollPos > sidebarPos.bottom ) {
+                    $sidebar.addClass('fixed-for-bottom');
+                    if ( scrollPos > sidebarPos.footer ) {
+                        $sidebar.addClass('fixed-on-footer');
+                    } else {
+                        $sidebar.removeClass('fixed-on-footer');
+                    }
+                } else {
+                    $sidebar.removeClass('fixed-for-bottom');
+                }
+            } else {
+                $sidebar.removeClass('fixed-for-top');
+            }
+        }
+    }
+    $(window).on('scroll', scrollScreen);
+    scrollScreen();
+});

File styles.css Added

  • Ignore whitespace
  • Hide word diff
+.sidebar{
+  position:relative;
+}
+.sidebar.fixed-for-bottom .sidebar-content {
+    position: fixed;
+    bottom: 0;
+}
+.sidebar.fixed-on-footer .sidebar-content{
+    position:absolute;
+}
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.