1

Is it possible to change the position of the scroll bar relative to a new hash tag? Currently, the page scrolls to the top of the element that is targeted using #target, which is normal behaviour. Is there a way to move it so the page scrolls to, for example, 100px further down the page than the anchor tag (adding an extra 100px before the anchor tag)?

Not sure whether cunning placement of the anchor or javascript should be used. Not sure I'm really able to change the position of the anchor so im hoping for a javascript solution.

Thanks

lowe_22
  • 395
  • 1
  • 5
  • 14

1 Answers1

2

You could combine the answer to this question: On - window.location.hash - Change?

With some extra logic:

$(function(){
  var win = $(window); //cache your jq objects!
  function fixScrollTop(){
    win.scrollTop(win.scrollTop() + 100);
  }
  if(window.location.hash !== ""){
    fixScrollTop();
  }
  win.bind('hashchange', fixScrollTop);
});

Oh, if you have control over the #anchor in the URL, you can (probably, depending on the browser compatibility you're shooting for) set it to the ID of any element with an ID to make the browser scroll to it.

Community
  • 1
  • 1
dtanders
  • 1,835
  • 11
  • 13
  • +1 for the combination with hashchange event — neat solution. Note that you can also animate `scrollTop`. Also, kind of a nit, but jQuery caches a reference to the window, so I don't think it is so crucial in this case. – harpo Sep 12 '11 at 18:40
  • Ah, nice idea. Thanks. Although I'm guessing the hashchange event only fires once the page has loaded, ie I'm already on that page and then change the hash? If I directly load a page `example.php#target` would that fire the hashchange on page load? – lowe_22 Sep 12 '11 at 19:05