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);
});