Search code examples
jquerycsspositionfixed

How to make div FIXED at the bottom when scroll down?


I've created a fiddle at

fiddle Link

All that I want is make the DIV#sticker FIXED at the bottom when scroll down until its bottom border (the bottom red border in my example) reaches the bottom of the browser window. How can I do that?

Thanks in advance!


Solution

  • You just need to calculate scroll offset + window height, to get the bottom part of the window, and then check if that is greater than element offset + element height. Also, you have to remove bottom margin from the element, if you really want it pinned down to the bottom border.

    Code is something like this:

    $(document).ready(function() {
        var s = $("#sticker");
        var pos = s.offset().top+s.height(); //offset that you need is actually the div's top offset + it's height
        $(window).scroll(function() {
            var windowpos = $(window).scrollTop(); //current scroll position of the window
            var windowheight = $(window).height(); //window height
            if (windowpos+windowheight>pos) s.addClass('stick'); //Currently visible part of the window > greater than div offset + div height, add class
            else s.removeClass('stick');
        });
    });
    

    I have edited your html a bit, so you can see it properly (added more scroll), but you can see the fiddle at http://jsfiddle.net/2UGgc/33/ or full-screen version at http://jsfiddle.net/2UGgc/33/show/