Javascript inline onclick goto local anchor

it looks the onClick should be:

onclick="document.location+='#goToPage';return false;" 

The solution presented in the accepted answer has the important issue that it can only be used 1 time. Each consecutive click appends #goToPage to location and the window won't navigate to the anchor.

A solution is to remove the anchor part before appending a new anchor:

function goToAnchor(anchor) {
  var loc = document.location.toString().split('#')[0];
  document.location = loc + '#' + anchor;
  return false;
}

Usage example:

<a href="#anchor" onclick="goToAnchor('anchor')">Anchor</a>

NOTE: The anchor needs to be enclosed in quotes, without the hash prefix.

Tags:

Javascript