iOS engineer who likes clean, simple designs and sans-serif.

Loading

Scrolling Links With No Anchor Tags In URL

I stumbled on a cool trick to allow a nav bar to scroll/link to certain sections on the page, without leaving a nasty hash tag #AnchorLink in the URL. Normally, if you click on an anchor link it will append a “#AnchorLink” to the end of the page’s URL. This isn’t a HUGE deal, except if the user then shares the URL, it will jump directly to that section, and not the top of the page. Here’s an example of what I mean:

When I click on the “Get Started” intra-page anchor link, I want the page’s URL to stay like this:

  https://generalassemb.ly/enterprise

I don’t want it to change to something like this:

  https://generalassemb.ly/enterprise#get-started

The below code will make sure “#get-started” doesn’t show up in the URL. Here’s the code (using jQuery):

HTML:

  <nav class="header-nav">
    <ul>
      <li><a class="waypoint-link" data-waypoint-id="enterprise-programs">Enterprise Education Programs</a></li>
      <li><a class="waypoint-link" data-waypoint-id="testimonials">Client Success Stories</a></li>
      <li><a class="waypoint-link" data-waypoint-id="get-started">Free Resources</a></li>
    </ul>
  </nav>

Javascript:

  $(".waypoint-link").on('click', function()
    var anchorID = $(this).data("waypoint-id");
    scrollToSection(anchorID);
  });

  function scrollToSection(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
  }

Leave a Comment