Anchor Links with Static Headers

Static site headers blocking anchor content
Tagged: UI/UXMonday, July 31, 2017

The Problem: Hidden Anchor Content

Anchor links normally scroll to the top of the browser when clicked. The problem is when your site has a static header will cause that content to be hidden underneath the sites header. Sometimes this could hide the entire element, leaving your visitors wondering what they are supposed to be looking at.

The Solution: Javascript

You can fix this with CSS or JS but the CSS method would normally involve you adding extra classes, or some other method of padding/margins that could throw off something else on the site.

I prefer the JS route since I won't have to go back and update all my pages, and should work out of the box with a lot of CMS software such as Drupal or Wordpress.

Note: this requires jQuery

$(function() {
  // Adjust anchors to work with static site header
  $(document).on("click", 'a[href^="#"]', function(e) {
    e.preventDefault();
    // Get the current target hash
    var target; // var to store match found
    var idTarget = this.hash; //#id-name w/hash from url
    var nameTarget = this.hash.substring(1); //remove hash
    var jqNameTarget = 'a[name="' + nameTarget + '"]';
    if ($(idTarget).length) {
      // There is an ID match
      target = $(idTarget);
    } else if ($(jqNameTarget).length) {
      // There is a name attribute match
      target = $(jqNameTarget);
    } else {
      // Cant find a name or ID so log error
      console.log("no link found on page.");
    }
    if (target && target.length) {
      // Animate to element instead of hard scroll
      $("html, body")
        .stop()
        .animate(
          {
            scrollTop: target.first().offset().top - 200,
          },
          350,
          "swing",
          function() {
            window.location.hash = idTarget;
          }
        );
    }
  });
});