Remove Scroll fixed from sidebar

1

I have this code that when the scroll moves it fixes the sidebar in the top, until then this correct now that when the sidebar approaches the footer, a scroll bottom, or something of the type is applied so that it follows the footer.

    <script>
      jQuery(window).scroll(function () {
      var threshold = 20;
      if (jQuery(window).scrollTop() >= 20)
      jQuery('.sidebar').addClass('fixed');
    else
      jQuery('.sidebar').removeClass('fixed');
    });
    </script>
    
asked by anonymous 30.07.2014 / 16:28

1 answer

0

If you want to make sidebar follow the limit of footer you need to know some more parameters / measures to make some accounts. I leave an example below. Ideally, you should have everything that is static out of function. That is all that has fixed measures:

var sidebar = jQuery('.sidebar');
var alturaFooter = jQuery('#footer').height();
var alturaPagina = jQuery('#pagina').height();
var alturaSidebar = sidebar.height();

So excuse me from re-calculating this every time the scroll is called.

Example: link

HTML

<div id="pagina">
    <header>Cabeçalho</header>
    <div class="sidebar">Sidebar</div>
    <footer>Footer</footer>
</div>

jQuery

var sidebar = jQuery('.sidebar');
var header = jQuery('header').height();
var alturaFooter = jQuery('footer').height();
var alturaPagina = jQuery('#pagina').height();
var alturaSidebar = sidebar.height();

jQuery(window).scroll(function () {

    // colar o sidebar
    var threshold = 20;
    var scroll = jQuery(window).scrollTop();
    if (scroll >= header) sidebar.addClass('fixed');
    else sidebar.removeClass('fixed');

    // seguir o footer
    if (scroll + alturaSidebar > alturaPagina - alturaFooter) sidebar.css('top', alturaPagina - scroll - alturaSidebar - alturaFooter);
    else sidebar.css('top', 0);

});
    
31.07.2014 / 00:25