2

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));
});
Seong Lee
  • 10,314
  • 25
  • 68
  • 106
  • There is no need of JavaScript workarounds. Modern web browser can handle this event natively with CSS `position: sticky;`. Have a read here: https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#position_sticky If you'll use the JS variation you will always have some unwanted glitches. The CSS solution is robust. – Michael W. Czechowski Mar 05 '19 at 07:57

3 Answers3

1

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

Zaichik
  • 308
  • 1
  • 7
1

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?

Stefan Surkamp
  • 972
  • 1
  • 16
  • 31
0

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.

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689