Skip to content Skip to sidebar Skip to footer

How Do I Add A Html Hash Link Without It Altering The Url Bar...?

When I add a HTML link to a specific part of the page: test I noticed that it changes the URL at the address bar. Although I have come across w

Solution 1:

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

<ahref="#scrollToMe"class="scrollLink">click me to scroll</a><divclass="gap">a big gap</div><h1id="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.

Solution 2:

It's possible to use javascript to intercept the click event, perform your own custom logic, then cancel the navigation event so the URL never changes

Solution 3:

Maybe you can try something like: window.scroll(0,150); instead of "(0,150)" put the cooridnate of your target.

Solution 4:

You'll have to experiment with the number (shown here as 200) to get the window to align properly.

<a href="javascript:void(0);" onclick="window.scroll(0,200);">test</a>

Solution 5:

You could use inline the next code:

<a href="javascript:void(0);" onclick="document.getElementById(\'bookmark\').scrollIntoView();"> link text </a>
<div id="bookmark">Jump to here</div>

Post a Comment for "How Do I Add A Html Hash Link Without It Altering The Url Bar...?"