Note that there are some explanatory texts on larger screens.

plurals
  1. POCannot use scrollTo offset when using window.location.hash
    text
    copied!<p>I have a single page site with a <code>position: fixed;</code> header containing main nav. I'm using <a href="http://flesler.blogspot.com/2007/10/jqueryscrollto.html" rel="nofollow"><strong>this plugin</strong></a> to smooth scroll to each section via the main nav. Because of the fixed header I need to set an <code>offset</code> which = height of the header. Everything works fine using this initialisation:</p> <pre><code>$('.nav-main a').click(function(e) { e.preventDefault(); var anchorLocation = $(this).attr('href'); $.scrollTo(anchorLocation, 700, { offset: -86 }); }); </code></pre> <p>But I need the URL to include the section ID e.g. <a href="http://domainname.com/#about" rel="nofollow">http://domainname.com/#about</a> which each link has in it's <code>href</code> e.g. <code>&lt;a href="#about"&gt;About&lt;/a&gt;</code> so I use this:</p> <pre><code>$('.nav-main a').click(function(e) { e.preventDefault(); var anchorLocation = $(this).attr('href'); $.scrollTo(anchorLocation, 700, { offset: -86, onAfter: function() { window.location.hash = anchorLocation; } }); }); </code></pre> <p>So that fixes up the URL but screws up the header in that sometimes it disappears once the smooth scroll has finished but then will come back into view if you scroll again and the <code>offset</code> just doesn't work. Any ideas?</p> <p><strong>EDIT</strong></p> <p>Someone posted the below solution but then removed it but it works in terms of not having to use the plugin but the <code>offset</code> only works in Webkit browsers (Chrome, Safari) in IE 8/9 &amp; Firefox once the scrolling animation has stopped it will honour the <code>offset</code> for about a millisecond then snap to the top of the viewport.</p> <pre><code>var headerHeight = $('[role="banner"]').outerHeight() -1; $('.nav-main a').click(function(e) { e.preventDefault(); scrollToID($(this).attr('href')); }); function scrollToID(ID){ $('html, body').animate({ scrollTop: $(ID).offset().top - headerHeight }, 700, function() { window.location.hash = ID; }); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload