0

I actually have a sticky menu which follow the scroll with this css :

.menuD {
  position: sticky;
  top : 190px;
}

The problem is that i would like him to be at this position when the user is at the top of the page (to align it with the other text) but i would like the menu to be at

top: 590px

when the user is at the bottom of the page. Do you have any idea how to do it ? I guess i need JS ...

Actually, the menu is going to high (because there is only 190px from top)

Thanks

LucB
  • 11
  • 4
  • I forgot : if the user is going top again, the top value have to go back to 190px – LucB May 07 '19 at 07:53
  • Yeah, you gotta use Javascript for that. Control the height of the viewport and assign a class to `.menuD` Depending on where the user is, `.menuD` will receive a class or another (with different top values) – M4FI4S May 07 '19 at 07:57
  • You may check out this: https://stackoverflow.com/questions/9439725/javascript-how-to-detect-if-browser-window-is-scrolled-to-bottom – Chaska May 07 '19 at 08:02
  • you should write a condition in user scroll. you should get page offset and apply class on tags. check this https://www.w3schools.com/jsref/prop_element_offsettop.asp – Arman Bagheri May 07 '19 at 08:36
  • ` guess i need JS` yes you do. Please try something first and then come back here so we can help you – Mihai T May 07 '19 at 08:37

1 Answers1

0

You can calculate if you are at the bottom of the page with scroll.

Here is a solution with pure javascript

Then add a class to the div using classList which defines the new css property. In this example: top: 590px instead of top: 190px

let menu = document.querySelector('.menuD');

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        menu.classList.add('bottom');
    } else {
      menu.classList.remove('bottom');
    }
};
body {
  height: 800px;
}

.menuD {
  position: absolute;
  top: 190px;
}

.bottom {
  top: 590px;
}
<div class="menuD">Menu</div>

JSFiddle Demo

Marc Hjorth
  • 1,797
  • 2
  • 18
  • 24
  • Performance wise it would be much better if you would use IntersectionObserver for this: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API Then you also don't have to permanently calculate the scroll position. – cloned May 07 '19 at 09:31
  • Didn't know about this, but it sure seems like a good solution :) You should make an answer – Marc Hjorth May 07 '19 at 10:33