Hat
Hat

Reputation: 1731

disable anchor tag

How would I go about putting a link on a page that changes the url, but doesn't change the page without using hash states?

I want to put links that change the url and scroll to a corresponding section of the page. I don't want to use hashes as they just jump to the section instead of scrolling, and I think hashes dont look very good in the url.

Upvotes: 1

Views: 724

Answers (4)

Blazemonger
Blazemonger

Reputation: 92893

Browsers now have security features that ensure that the URL displayed in the location bar matches what's actually being displayed. You can't change the location without changing the page at the same time.

However, you can scroll the page anywhere you like without changing the URL. To scroll to a particular element, get its position and use .animate():

$('body').animate({scrollTop: $('#element').position().top});

​ Combine this with an .on('click',...) handler that uses e.preventDefault() to cancel the URL change and you're good to go.

$('a[href^=#]').on('click', function(e) { // apply to all hash links
    var el = $(this).attr('href');        // get the href
    e.preventDefault();                   // cancel default click action
    $('body').animate({
        scrollTop: $(el).position().top   // scroll to the href ID instead
    });
});​

http://jsfiddle.net/mblase75/WFKUE/

Upvotes: 1

Jim Blackler
Jim Blackler

Reputation: 23169

HTML5 browser history (aka PushState) is the modern approach

https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history

It is fairly widely supported in browsers

http://caniuse.com/history

Upvotes: 0

ajtrichards
ajtrichards

Reputation: 30565

Have you tried the jQuery ScrollTo plugin? http://archive.plugins.jquery.com/project/ScrollTo

Upvotes: 3

0x6A75616E
0x6A75616E

Reputation: 4716

Take a look at HTML5 Push State

There is no other way as far as I know.

Upvotes: 3

Related Questions