Menu icon Foundation
Sticky Sidebar - but not for mobile view

Hello everybody!

I found this nice and simple trick to create a sticky sidebar (http://zurb.com/building-blocks/sticky-sidebar). Now I wonder whether it is possible to change some of the code so that the script does not apply to the mobile view. The way the sidebar is displayed now is not very elegant.

sidebarstickysmall

Hello everybody!

I found this nice and simple trick to create a sticky sidebar (http://zurb.com/building-blocks/sticky-sidebar). Now I wonder whether it is possible to change some of the code so that the script does not apply to the mobile view. The way the sidebar is displayed now is not very elegant.

Rafi Benkual about 4 years ago

You can remove the sticky class with jQuery based on window size. Something like this:

Javascript 
 function sideNav() {
  if ($(window).width() < 769) {
    $('.sidebar').removeClass('sticky');
  } else {
    $('.sidebar').addClass('sticky');
  }  
}

$(window).resize(function() {
  sideNav();
});

Or you can hide it with visibility classes and show a different version that fits the screen better.

Magda Jans about 4 years ago

Good morning, and thanks a lot for this reply. The visibility classes work in fact. But for me a js-solution still would be good; it has something to do with the special look of the navigation that I placed into the sidebar. (Regrettably no link available right now.)

Now I tried to apply the snippet you suggested, but I still don't get the thing to work. I have only a minimal understanding of javascript (logical thinking mostly...), so would you mind to have another look at this?

Here is the code of the js:

 $(document).ready(function(){var stickySidebar = $('.sticky');

if (stickySidebar.length > 0) { 
  var stickyHeight = stickySidebar.height(),
      sidebarTop = stickySidebar.offset().top;
}

// on scroll move the sidebar
$(window).scroll(function () {
  if (stickySidebar.length > 0) { 
    var scrollTop = $(window).scrollTop();

    if (sidebarTop < scrollTop) {
      stickySidebar.css('top', scrollTop - sidebarTop);

      // stop the sticky sidebar at the footer to avoid overlapping
      var sidebarBottom = stickySidebar.offset().top + stickyHeight,
          stickyStop = $('.main-content').offset().top + $('.main-content').height();
      if (stickyStop < sidebarBottom) {
        var stopPosition = $('.main-content').height() - stickyHeight;
        stickySidebar.css('top', stopPosition);
      }
    }
    else {
      stickySidebar.css('top', '0');
    } 
  }
});

$(window).resize(function () {
  if (stickySidebar.length > 0) { 
    stickyHeight = stickySidebar.height();
  }
});})