Skip to main content
2 of 9
handle comment links too
user3840170
  • 385
  • 1
  • 10

Faster Answer Links

This is a convenience user script. It prevents page reloading when following links to answers that happen to be present on the same page, and to their comments; instead, it simply scrolls to the link target on the current page.

// ==UserScript==
// @name     Stack Exchange: Faster Answer Links
// @grant    none
// @run-at   document-start
// @match    https://*.stackexchange.com/*
// @match    https://*.superuser.com/*
// @match    https://*.stackoverflow.com/*
// @match    https://*.mathoverflow.net/*
// @match    https://*.serverfault.com/*
// @match    https://*.askubuntu.com/*
// @match    https://stackapps.com/*
// @exclude  https://chat.stackexchange.com/*
// @exclude  https://api.stackexchange.com/*
// @exclude  https://data.stackexchange.com/*
// @exclude  https://openid.stackexchange.com/*
// @exclude  https://contests.stackoverflow.com/*
// @exclude  /^https?:\/\/winterbash\d{4,}\.stackexchange\.com\//
// ==/UserScript==

document.addEventListener('click', ev => {
  if (ev.defaultPrevented)
    return;

  const target = ev.target.closest(':any-link');
  if (!target)
    return;

  const u = new URL(target.href);
  if (u.origin !== location.origin)
    return;

  let m;

  if (/^\/(q|a|questions)\//u.test(u.pathname)
      && (m = /^#comment\d+_(\d+)$/u.exec(u.hash))) {
    if (!document.querySelector(`
      #answer-${m[1]}, #question[data-questionid="${m[1]}"]`))
      return;
    ev.preventDefault();
    location.href = u.hash;
    return;
  }
  
  if (u.hash)
    return;

  if (m = /^(?:\/a\/|\/questions\/[^\/]+\/)(\d+)(?=\/|$)/u.exec(u.pathname)) {
    if (!document.getElementById(`answer-${m[1]}`))
      return;
    ev.preventDefault();
    location.href = '#answer-' + m[1];
    return;
  }
}, false);
user3840170
  • 385
  • 1
  • 10