Prevent href="#" link from changing the URL hash

Please read up on Progressive Enhancement and Unobtrusive JavaScript.

You should (almost) never have href="#". It is a link to an undefined anchor (which will be the top of the page). People who use it normally do so because they want to dangle JavaScript off it.

If you are going to have a link, then it should point to somewhere useful. Typically this will be another page that uses server side technology to get the same effect (albeit less quickly) as the JavaScript would give. You can then prevent the normal behaviour of the link.

For example:

<a href="/foo/bar" class="whatever">Foo: Bar</a>

With the script:

addEventListener('click', function (ev) {
    if (ev.target.classList.contains('whatever')) {
        ev.preventDefault();
        loadWithAjax(ev.target.href);
    }   
});

If the JavaScript does something that can't have equivalent functionality expressed in a link, then you shouldn't be using a link in the first place. Use a <button>, and seriously consider adding it to the document using JavaScript/DOM instead of HTML.

(NB: Quite a lot of people want to support older browsers which don't recognise classList or addEventListener checking browser support and finding compatibility routines is left as an exercise for the reader. Using YUI, jQuery or similar is one approach for dealing with compatibility.)


Instead of having # in href, you can use javascript:; in href which will not let the url change.

<a href="javascript:;">:Link</a>

You can listen for the click event and call preventDefault to stop the browser from setting the hash.

Example with jQuery:

$('.mylink').click(function(event){
    event.preventDefault();
});