Fixed (sticky) toolbars with jQuery

Here’s a little snippet of code that let’s you create sticky toolbars like they use in Magento for example :)

Include this in your js somewhere and then just call $(‘.toolbar’).fixed();

$.fn.fixed = function() {
    return this.each(function() {
        var header = $(this);
        var offset = header.offset();
        var floater = $('<div></div>').append(header.clone(true));
        floater.hide().appendTo(document.body).addClass('floating-toolbar');

        $(window).scroll(function() {
            var s = $(this).scrollTop();

            if (s > offset.top) {
                header.css('visibility', 'hidden');
                floater.show();
            } else {
                floater.hide();
                header.css('visibility', 'visible');
            }
        });
    });
};

And here’s some css to make it work.

.floating-toolbar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    opacity: 0.85;
}
19/01/2010 at 5:16 pm — Filed under: Javascript

No Comments »

No comments yet.

Leave a comment