DEV Community


Fixed element on scroll past

creativezest2021 profile image creativezest2021 ・1 min read

Hi people!

I hope everyone is well.

I have a coding issue and could really do with some help...

I have a page with a fixed top bar and a section menu that fixes to the bottom of the viewport on small devices and at the top, below the top bar, on devices with viewports wider than 1080px.

There's also an element at a certain point down the page that when the user scrolls past it, it fixes to the top of the viewport.

I've managed to get all of this to work but the issue is that I cannot seem to adjust the distance at which the element fixes from the top of the viewport. In other words it needs to be fixed at top: 75px on screens less than 1080px and top: 140px on screens larger than 1080px.

This is to cater for the fact that the section menu is either fixed at the bottom of the viewport on mobile and below the top bar on desktop.

I've created a minimal demo in codepen to demonstrate this where I have placed the required javascript for the main functions within a match media query, in an attempt to make this top adjustment.

However, as you will see, it simply applies the highest setting (140px) which results in a gap between the top bar and the fixed element on smaller screens.

Here's the codepen:

I'd really appreciate any help at all.

Many thanks in advance.



Editor guide