Stick Sidebar To The Bottom Of The Page When Scrolled Through

Don’t let important short sidebars disappear when visitors scroll though the web page. In this article I’m going to present how to stick a HTML element, to the bottom of the page with JavaScript when it’s about to disappear. I have already presented the way of attaching it to the top of the page and this method is very similar to that.
stick bottom


Check out the demonstration and come back for the explanation:

Live demo (jsFiddle)

HTML

...
<div id="stickThis">
  Sidebar
</div>
<div id="stick-here"></div>
...

Of course, your HTML will contain much more than this example. These are just the wrapping elements. We have the stickThis section, wrapping everything that needs to me attached. The dots represent that anything may come before and after this section. The stick-here element is necessary because we use that for detecting when the bottom of the section has been reached.

JavaScript

function sticktothebottom() {
    var h = window.innerHeight;
    var window_top = $(window).scrollTop();
    var top = $('#stick-here').offset().top;
    var panelh = $("#stickThis").height();
    if (window_top + h > top + 22) {
        $('#stickThis').addClass('stick');
        $('#stick-here').height($('#stickThis').outerHeight());
    } 
    if (window_top + top < panelh + (22 * 2)) {
        $('#stickThis').removeClass('stick');
        $('#stick-here').height(0);
    }
}
$(function() {
    $(window).scroll(sticktothebottom);
    sticktothebottom();
});

The JavaScript function is fired every time the page is being scrolled. The sticktothebottom function evaluates the position of the elements and decides whether to attach or detach the elements. It assigns or removes the stick class.

CSS

#stickThis {
    padding: 5px;
    background-color: #ccc;
    font-size: 1.5em;
    width: 300px;
    text-align: center;
    font-weight: bold;
    border: 2px solid #444;
    border-radius: 10px;
}
#stickThis.stick {
    margin-top: 0;
    position: fixed;
    bottom: 22px;
    z-index: 9999;
    border-radius: 0 20px 20px 0px;
}

The style is different when the section is scrolling freely and when it’s attached to the bottom. You can adjust these styles to match your design.