append /remove anchor name from current url without refresh

You don’t really need jQuery for that, you can get/set the anchor name using location.hash. If you put it in your jQuery ready function, you can do some action if it’s set to a certain value:

$(function(){
    // Remove the # from the hash, as different browsers may or may not include it
    var hash = location.hash.replace('#','');

    if(hash != ''){
        // Show the hash if it's set
        alert(hash);

        // Clear the hash in the URL
        location.hash="";
    }
});

Note that when removing the hash, the trailing # might stay in the address bar. If you want to respond to live changes of the anchor, you can bind a callback to the hashchange event:

$(document).bind("hashchange", function(){
    // Anchor has changed.
});

If you want to prevent your page jumping to the top when clearing the anchor, you can bind the hashchange event to jump back to the previous scroll position. Check out this example: http://jsfiddle.net/yVf7V/

var lastPos = 0;

$('#on').click(function(){
    location.hash="blah";
});

$('#off').click(function(){
    lastPos = $(window).scrollTop();
    location.hash="";
});

$(window).bind('hashchange',function(event){
    var hash = location.hash.replace('#','');
    if(hash == '') $(window).scrollTop(lastPos);
    alert(hash);
});

Leave a Comment