Skip to content
Advertisement

Modifying location.hash without page scrolling

We’ve got a few pages using ajax to load in content and there’s a few occasions where we need to deep link into a page. Instead of having a link to “Users” and telling people to click “settings” it’s helpful to be able to link people to user.aspx#settings

To allow people to provide us with correct links to sections (for tech support, etc.) I’ve got it set up to automatically modify the hash in the URL whenever a button is clicked. The only issue of course is that when this happens, it also scrolls the page to this element.

Is there a way to disable this? Below is how I’m doing this so far.

$(function(){
    //This emulates a click on the correct button on page load
    if(document.location.hash){
     $("#buttons li a").removeClass('selected');
     s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
     eval(s);
    }

    //Click a button to change the hash
    $("#buttons li a").click(function(){
            $("#buttons li a").removeClass('selected');
            $(this).addClass('selected');
            document.location.hash=$(this).attr("id")
            //return false;
    });
});

I had hoped the return false; would stop the page from scrolling – but it just makes the link not work at all. So that’s just commented out for now so I can navigate.

Any ideas?

Advertisement

Answer

I think I may have found a fairly simple solution. The problem is that the hash in the URL is also an element on the page that you get scrolled to. if I just prepend some text to the hash, now it no longer references an existing element!

$(function(){
    //This emulates a click on the correct button on page load
    if(document.location.hash){
     $("#buttons li a").removeClass('selected');
     s=$(document.location.hash.replace("btn_","")).addClass('selected').attr("href").replace("javascript:","");
     eval(s);
    }

    //Click a button to change the hash
    $("#buttons li a").click(function(){
            $("#buttons li a").removeClass('selected');
            $(this).addClass('selected');
            document.location.hash="btn_"+$(this).attr("id")
            //return false;
    });
});

Now the URL appears as page.aspx#btn_elementID which is not a real ID on the page. I just remove “btn_” and get the actual element ID

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement