Note that there are some explanatory texts on larger screens.

plurals
  1. POAccounting for a fixed header with animate.scrolltop and (target).offset().top;
    text
    copied!<p>This should be a pretty basic question, but i've thrown most of my morning at it, and at this point I'm close to throwing in the towel. I have not even a little bit of js foo -- but I found a nicely commented chunk of code that I'm hoping to use to animate anchor links it is:</p> <pre><code>$(document).ready(function() { $('a[href*=#]').bind('click', function(e) { e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump var target = $(this).attr("href"); //Get the target var scrollToPosition = $(target).offset().top; // perform animated scrolling by getting top-position of target-element and set it as scroll target $('html, body').stop().animate({ scrollTop: scrollToPosition}, 600, function() { location.hash = target; //attach the hash (#jumptarget) to the pageurl }); return false; }); }); </code></pre> <p>I'm trying to get it to land 30px above the offset().top -- I tried </p> <p><code>$('html, body').stop().animate({ scrollTop: scrollToPosition -30}, 600,</code></p> <p>Which almost works -- it goes to the right place but then bounces back.</p> <p>I've also tried </p> <p><code>scrollTop: $(target).offset().top - 20 },</code></p> <p>I've also tried</p> <p><code>scrollTop: $(hash).offset().top + $('#access').outerHeight()</code></p> <p>Which doesn't seem to change anything. </p> <p>It seems like the answer might be here: <a href="https://stackoverflow.com/questions/6295771/jquery-page-scroll-issue-with-fixed-header">JQuery page scroll issue with fixed header</a> but I just can't quite seem to get it. </p> <p>I know this is similar to other questions -- but I've gone through what I could find and I'm illiterate enough that I haven't been able to copy/paste in anything that fixes the issue.</p> <p>I'd be incredibly grateful for a solution. </p> <p>Many thanks,</p> <p>Martin </p> <p>PS</p> <p>This other chunk of code I found does work but it's stripping the hashtag out, which makes it mostly useless. </p> <pre><code>$(function(){ $('a[href*=#]').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') &amp;&amp; location.hostname == this.hostname) { var $target = $(this.hash); $target = $target.length &amp;&amp; $target || $('[name=' + this.hash.slice(1) +']'); if ($target.length) { var targetOffset = $target.offset().top; $('html,body').animate({scrollTop: targetOffset - 30}, 1000); return false; } } }); }); </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