version_warning_offset.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /*
  2. When showing the sticky version warning, the warning will cover the
  3. scroll target when navigating to #id hash locations. Take over scrolling
  4. to adjust the position to account for the height of the warning.
  5. */
  6. $(() => {
  7. const versionWarning = $('.version-warning')
  8. // Skip if there is no version warning, regular browser behavior is
  9. // fine in that case.
  10. if (versionWarning.length) {
  11. const height = versionWarning.outerHeight(true)
  12. const target = $(':target')
  13. // Adjust position when the initial link has a hash.
  14. if (target.length) {
  15. // Use absolute scrollTo instead of relative scrollBy to avoid
  16. // scrolling when the viewport is already at the bottom of the
  17. // document and has space.
  18. const y = target.offset().top - height
  19. // Delayed because the initial browser scroll doesn't seem to
  20. // happen until after the document ready event, so scrolling
  21. // immediately will be overridden.
  22. setTimeout(() => scrollTo(0, y), 100)
  23. }
  24. // Listen to clicks on hash anchors.
  25. $('a[href^="#"]').on('click', e => {
  26. // Stop default scroll. Also stops the automatic URL hash update.
  27. e.preventDefault()
  28. // Get the id to scroll to and set the URL hash manually.
  29. const id = $(e.currentTarget).attr('href').substring(1)
  30. location.hash = id
  31. // Use getElementById since the hash may have dots in it.
  32. const target = $(document.getElementById(id))
  33. // Scroll to top of target with space for the version warning.
  34. scrollTo(0, target.offset().top - height)
  35. })
  36. }
  37. })