Edit: Seems the collapsing thing works well after I added popper JS to the pen, hinted by this post. Perhaps its a dependency or something.
Conclusion: when adopting bootstrap API, don’t use the one-click bootstrap 4 inside CodePen. Check out the Bootstrap Documentation - Introduction, copy the URLs inside the HTML snippets and add them manually. This ensures that you get the newest version, minimal format, and full dependencies.
Edit: scrollspy solved, too. After adding pooper, the only thing left is to change the style of the spied-on element. Note that the documentation says:
It must be used on a Bootstrap nav component(navbar also works) or list group.
Scrollspy requires position: relative; on the element you’re spying on, usually the<body>.
When spying on elements other than the <body>, be sure to have a height set and overflow-y: scroll; applied.
Anchors (<a>) are required and must point to an element with that id.
The 2nd and 3rd items are easily ignored if we intuitively spy on a container/container-fluid rather than on the <body> and adjust offset.
Another edit: Also note that the jQuery link in the Bootstrap doc is a slim version. If you need animate or other functions, delete the .slim in the URL to import the full one. Inspired by This Stackoverflow question