06 Jul

jQuery base href named anchors fix

Any web developer who uses <base href> tags in their sites has eventually run into the named anchors problem.  Essentially, anchor links (e.g. <a href="#testanchor">) which, when clicked, position the browser at a pre-defined point break when using <base href> tags because the link is considered relative to the base URL.  So, the user ends up in your base href directory and not at the place they were meant to be.

However, with the simple bit of jQuery javascript below, you can rewrite all anchor links on a page to work correctly.  It's SEO-friendly, easy, and semantically-sensible.

To use the fix, simply paste the following JavaScript code in the <head></head> section of your webpage HTML code.  Links will rewrite automatically.

<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery("a[ href ^= '#' ]").each(function() {
        var href = window.location + jQuery(this).attr('href').replace('/#.*/i','');
        jQuery(this).attr('href',href);
    });
});
</script>

Comments

No comments have been posted yet.
Post a comment
  1. You must be logged in to post a comment.
  2. Must be less than 400 characters. Allowed HTML tags: <a>, <b>, <i>, <u>.