Skip to main content

Modifying document.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?



Source: Tips4all

Comments

  1. Step 1: You need to defuse the node ID, until the hash has been set. This is done by removing the ID off the node while the hash is being set, and then adding it back on.

    hash = hash.replace( /^#/, '' );
    var node = $( '#' + hash );
    if ( node.length ) {
    node.attr( 'id', '' );
    }
    document.location.hash = hash;
    if ( node.length ) {
    node.attr( 'id', hash );
    }


    Step 2: Some browsers will trigger the scroll based on where the ID'd node was last seen so you need to help them a little. You need to add an extra div to the top of the viewport, set its ID to the hash, and then roll everything back:

    hash = hash.replace( /^#/, '' );
    var fx, node = $( '#' + hash );
    if ( node.length ) {
    fx = $( '<div></div>' )
    .css({
    position:'absolute',
    visibility:'hidden',
    top: $.scroll().top + 'px'
    })
    .attr( 'id', hash )
    .appendTo( document.body );
    node.attr( 'id', '' );
    }
    document.location.hash = hash;
    if ( node.length ) {
    fx.remove();
    node.attr( 'id', hash );
    }


    Step 3: Wrap it in a plugin and use that instead of writing to location.hash...

    ReplyDelete
  2. 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

    ReplyDelete
  3. I don't think this is possible. As far as I know, the only time a browser doesn't scroll to a changed document.location.hash is if the hash doesn't exist within the page.

    This article isn't directly related to your question, but it discusses typical browser behavior of changing document.location.hash

    ReplyDelete
  4. lazyweb, lazy answer -
    why don't you just move the element you're linking to into view?
    have you tried using position:static?
    what happens when the specified id has display:none?

    ReplyDelete
  5. A snippet of your original code:

    $("#buttons li a").click(function(){
    $("#buttons li a").removeClass('selected');
    $(this).addClass('selected');
    document.location.hash=$(this).attr("id")
    });


    Change this to:

    $("#buttons li a").click(function(e){
    // need to pass in "e", which is the actual click event
    e.preventDefault();
    // the preventDefault() function ... prevents the default action.
    $("#buttons li a").removeClass('selected');
    $(this).addClass('selected');
    document.location.hash=$(this).attr("id")
    });

    ReplyDelete
  6. The other way to do this is to add a div that's hidden at the top of the viewport. This div is then assigned the id of the hash before the hash is added to the url....so then you don't get a scroll.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.