How do I add a HTML hash link without it altering the URL bar...?

Alehandro Darie picture Alehandro Darie · Nov 25, 2011 · Viewed 8.5k times · Source

When I add a HTML link to a specific part of the page:

<a href="#specific">test</a>

I noticed that it changes the URL at the address bar. Although I have come across websites where they link that way without the address bar being updated. How is this possible?

EDIT: It might be an AJAX solution were they make it work without URL change, as if I remember correctly, the page didn't reload, it went directly to the destination...

Answer

Alex KeySmith picture Alex KeySmith · Nov 25, 2011

You may wish to look at the jquery plugin, scrollTo.

http://jquery.com

And a couple of links for scrollTo

http://demos.flesler.com/jquery/scrollTo/

http://flesler.blogspot.com/2007/10/jqueryscrollto.html

You can do something like this:

The HTML

<a href="#scrollToMe" class="scrollLink">click me to scroll</a>
<div class="gap">a big gap</div>
<h1 id="scrollToMe">I should scroll to here without a # in the URL</h1>

The javascript (jquery and the scrollto plugin)

$(document).ready(function() {
    $(".scrollLink").click(function(e) {

        $.scrollTo($(this).attr("href"));    
        e.preventDefault();

    });

});

What the javascript does, is when ever a link is clicked that has the class ".scrollLink", scroll the page down to the element that has the same ID, as the href for the particular link clicked. Then the e.preventDefault() stops it working like the normal hash link and stops it appearing in the URL bar.

Here is a working example for you: http://jsfiddle.net/alexkey/c3jsY/7/

And a version not in a frameset, so you can see that the URL doesn't change:

http://fiddle.jshell.net/alexkey/c3jsY/7/show/light/

This approach has a couple of good points

  1. Simply apply the scrollLink class to links you want to stop the hash appearing (nice and easy)
  2. It uses the normal href, which also means the links will still work even if javascript is disabled - good for accessibility and probably search engine optimisation to.