Slava Knyazev
Slava Knyazev

Reputation: 6081

What can I do to simulate Position:Sticky?

If you do not know what position:sticky is, watch this 20 second long video: https://www.youtube.com/watch?v=jA67eda5i-A .

This CSS feature was in talks in W3 and implemented in gecko I believe. But that is besides the point, the point is that not all browsers support it and I really want that functionality.

Is there any way I can get this using a mix of CSS and/or javascript and/or jquery?

Upvotes: 0

Views: 2434

Answers (2)

Laurent
Laurent

Reputation: 519

To avoid using a plugin, i have created the following javascript method using jquery 1.8+.

The first argument is the element that you want to set sticky. The second argument is optionnal and is a boolean to enhance the browser performance by setting a small timeout of 300ms.

function simulateSticky(elt, timeout) {
    var move = function() {
        var scrollTop = $(window).scrollTop();
        var scrollBottom = $(document).height() - scrollTop - $(window).height();

        var eltTop = elt.parent().offset().top;
        var eltBottom = $(document).height() - eltTop -  elt.parent().outerHeight();

        if (scrollTop < eltTop) { // Top case
            elt.css({
                position: "absolute",
                width: "100%",
                top:"auto",
                right: "0px",
                bottom: "auto",
                left: "0px",
            });
        }
        else if (scrollTop >= eltTop && scrollBottom >= eltBottom) { // Middle case
            elt.css({
                position: "fixed",
                width: elt.parent().outerWidth(),
                top:"0px",
                right: "auto",
                bottom: "auto",
                left: "auto",
            });
        }
        else { // Bottom case
            elt.css({
                position: "absolute",
                width: "100%",
                top:"auto",
                right: "0px",
                bottom: "0px",
                left: "0px",
            });
        }
    };

    // Use of a timeout for better performance
    if (timeout) {
        var timeoutId;
        $(window).scroll(function() {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function() {
                move();
            }, 300);
        });
    }
    else {
        $(window).scroll(move);
    }

    // Initial call
    move();
}

Upvotes: 1

cport1
cport1

Reputation: 1185

There is an easy jquery plugin for this:: http://stickyjs.com/

Upvotes: 2

Related Questions