Question

How can I tell if an element is scrolled behind another element fixed at the top?

What I want to do is run some javascript when an element is underneath a fixed element and every height or scrollTop after that.

I am trying to do a sticky header, but I can't just do fixed positioning on a scrollTop because the element I am sticky positioning is pushed down as the viewport becomes smaller, which means a different scrollTop is needed to fix the element then.

That is why I was thinking that it would be easier to fix / sticky the element when it is under an element already fixed at the top.

I have tried: position:sticky; with its vendor-prefixes with these two polyfills:

Était-ce utile?

La solution

Have a look at Sticky Kit, it looks like it's got the functionality you need to handle your situation: http://leafo.net/sticky-kit/

Most importantly you can raise an event to tell it to recalculate the sticky positions when your content changes.

For example:

$(window).on('resize', function(){
    $(document.body).trigger('sticky_kit:recalc');
});

Edit:

I've had a quick look at your site.

To get this to work you need to move your #filter and #main elements to a shared parent under <body> - so not a direct child of <body>:

<body>
    <div>
        <section id="filter">
            ...
        </section>
        <main id="main">
            ...
        </main>
    </div>
</body>

Then in your main.js file remove the entire $(window).scroll() handler, it's not needed. For the most part let sticky-kit handle the calculations for where the element needs to sit:

// Removed $(window).scroll(...)
$('#filter').stick_in_parent();

$(window).on('resize', function(){
    $(document.body).trigger('sticky_kit:recalc');
});

Finally you will need to raise the 'sticky_kit:recalc' event after your animation and slideToggle effects have finished to make sure the fixed elements end up in the right spot. If you don't do this then your stickied element will try to cover the whole page or do other weird things.

Good luck with it!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top