Add JavaScript for fragment jumper
As a result of using a fixed navbar, when navigating to an in-page reference (i.e., fragment), the target of the reference disappears underneath the navbar. We need to address this problem.
There are two ways to solve this problem:
- Add extra padding to the top of the target to compensate for the navbar height.
- Use a script that responds to an in-page navigation and corrects the scroll offset accordingly.
The problem with solution (1) is that it's extremely invasive to the design. It works okay for section titles, which already have top padding. However, handling inline elements requires sophisticated layout hacks. Since AsciiDoc offers the ability to link to an anchor almost anywhere, this is simply not a viable solution.
This is a case where JavaScript (2) is the right tool for the job. The JavaScript can intercept an in-page navigation and easily correct for the scroll offset. This solution requires no configuration or hacks.
The JavaScript should implement the following behavior:
- query the anchors for all in-page references (i.e., an
<a>
with anhref
that begins with#
) - bind a click handler that overrides the default behavior and handles jumping to the anchor (i.e., target)
- gracefully ignores any in-page references that cannot be resolved
- responds to the page load event and jumps to the anchor corresponding to the fragment requested in the URL*
* It's necessary to use the load event instead of the DOMContentLoaded since the jump offset cannot be accurately calculated until the page is fully loaded.
The JavaScript file should be named 02-fragment-jumper.js so it's loaded after the navigation script. The navigation script affects the rendering of the page, so it needs to come first.