1

I see this UX a lot, where there is a floating sidebar, that shows you where you are in the table-of-contents as you scroll through the page. This is a good example:

https://www.ycombinator.com/rfs/

I've occasionally found some libraries for this (e.g. in Semantic-UI), but what I'd really like is a lighter-weight approach, perhaps just with some vanilla javascript, so that I can continue using my site's assets/CSS/etc.

If important, my site uses ReactJS.

Any directions on how to best implement this? Many thanks!

  • You just need to add scroll detection with JS, once the user scrolls to the top of the element you want to fix, you just add a class that has `position:fixed;` to the element and then remove it once they scroll back above the top of the element. You definitely shouldn't need a library for this. – APAD1 Dec 12 '18 at 20:10
  • Thank you! Yes, that looks right, but there's a lot of other things in that demo, e.g. that a "highlight" formatting cycles through table of contents as you scroll down the page. I see this in so many places now, that I'm just assuming there's a standardized way to do it... – Daniel Axelsen Dec 12 '18 at 20:34
  • No standardized way, but there are many different techniques detailed here on SO such as: [Change Active Menu Item on Page Scroll?](https://stackoverflow.com/questions/9979827/change-active-menu-item-on-page-scroll) – APAD1 Dec 12 '18 at 20:43
  • Ah, okay. I was going to avoid jquery, but I think this helps me figure it out. Thanks! – Daniel Axelsen Dec 12 '18 at 21:06
  • [It can be accomplished with Vanilla JS as well](https://stackoverflow.com/questions/52025615/vanilla-js-change-active-state-of-links-when-scrolling-refactoring) – APAD1 Dec 12 '18 at 21:25

1 Answers1

0

Here's an example of the method I described above:

var scrollPos = window.scrollY,
    fixedEle = document.querySelector('aside'),
    fixedElePos = fixedEle.offsetTop;

window.addEventListener('scroll', function() {
  scrollPos = window.scrollY;

  if (scrollPos >= fixedElePos) {
    fixedEle.classList.add('fixed');
  } else {
    fixedEle.classList.remove('fixed');
  }
});
.container {
  height:3000px;
  padding-top:150px;
}
aside {
  position:relative;
  top:0;
}
  aside.fixed {
    position:fixed;
  }
<div class="container">
  <aside>
    This element should be fixed on scroll
  </aside>
</div>
APAD1
  • 13,509
  • 8
  • 43
  • 72