Seong Lee
Seong Lee

Reputation: 10580

Multiple sticky elements on scroll

I have header and sidebar div blocks and for our specific needs, I need to make both elements stick at the top once scroll event fires.

Making single element sticky is no problem but if there is more than one, it prevents scroll action and keeps jumping back to the top.

Is there any nice solution to this without using plugins?

Here is my JS Fiddle

And, the following is the script which works well with single element.

$(window).on("scroll", function () {
    var fromTop = $(window).scrollTop();
    $(".sidebar").toggleClass("fixed", (fromTop > 50));
    $(".header").toggleClass("fixed", (fromTop > 50));
});

Upvotes: 2

Views: 5375

Answers (3)

Simon_Weaver
Simon_Weaver

Reputation: 146208

Surprised so few answers to this.

If you have two sticky items you want to keep as separate elements, perhaps in different wrapperrs the key is to put top: 50px on the second sticky item (or whatever the height of the first is) so it gets 'stuck' at that position and doesn't cover the first.

There's also lots of reasons sticky can 'fail' or break. This question has lots of scenarios.

Upvotes: 0

Stefan Surkamp
Stefan Surkamp

Reputation: 992

A more simple HTML/CSS-only solution would be, to add

position: fixed;

to both of the div containers right from the beginning. Thus they're always fixed no matter if the user already scrolled or not. See the solution here: http://jsfiddle.net/N4maR/3/

I don't see a special reason why it should just be fixed after a certain threshold?

Upvotes: 1

Zaichik
Zaichik

Reputation: 306

More like this:

$(window).on('scroll', function () {

    var windowTop = $(window).scrollTop();
    var elementTop = $('.anchor').offset().top;

    if(windowTop > elementTop) {
        $(".sidebar").addClass("fixed");
        $(".header").addClass("fixed");
    } else {
        $(".sidebar").removeClass("fixed");
        $(".header").removeClass("fixed");
    }

});

JS Fiddle

Upvotes: 1

Related Questions