How can I return to a named anchor after scrolling in Chrome?

Solution 1:

You can simply execute some JavaScript to scroll the element to the top of the view:

document.getElementById(location.hash.slice(1)).scrollIntoView()

Source: javascript - How to scroll HTML page to given anchor? - Stack Overflow

For convenience, it's possible to add this as a bookmark on the bookmark bar, or define a keyboard shortcut for it.

javascript:document.getElementById(location.hash.slice(1)).scrollIntoView()

When there's no hash in the URL, it'll cause a (silent) JavaScript error. To scroll to the top of the page instead use

(document.getElementById(location.hash.slice(1))||document.body).scrollIntoView()

Solution 2:

Use this bookmarklet:

javascript: var h = location.hash ; location.hash = "" ; location.hash = h ; null

Explanation:

  • Setting location.hash will cause the page to scroll to that anchor.
  • As a special case, setting location.hash to itself is a no-op.
  • It does scroll, however, if we set it to something else and then immediately back to the original value.
  • Finally, bookmarklets must have null/undefined as their final value or (for historical reasons) they replace the page body with their final value.

[The following is just for "extra credit"]

Alternatively, we could do something along the lines of user202729’s answer. His answer only works with anchors formed by <a id="foo">. They don’t work with anchors that use <a name="foo">, e.g. those used here on SU/SO/SE! We can catch those (possibly with false positives -- I didn't explore this approach so much) with

javascript: var h = location.hash.slice(1) ; (document.getElementById(h) || document.getElementsByName(h)[0] || document.body).scrollIntoView()

However even that approach fails on sites like github.com which use <a class="anchor" href="#foo">. AFAICT, that approach is non-standard and requires custom javascript. My initial approach above works on all three anchor styles.

p.s. I love the collaboration of ideas that can come from SE. Reading user202729’s answer along with Dean Harding’s answer to How to scroll HTML page to given anchor? gave me the ideas I needed to experiment and noodle my way to my answer.