Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Update April 2018:</strong> There's now <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView" rel="noreferrer">a native way to do this</a>:</p> <pre class="lang-js prettyprint-override"><code>document.querySelectorAll('a[href^="#"]').forEach(anchor =&gt; { anchor.addEventListener('click', function (e) { e.preventDefault(); document.querySelector(this.getAttribute('href')).scrollIntoView({ behavior: 'smooth' }); }); }); </code></pre> <p>This is currently only supported in the most bleeding edge browsers.</p> <hr> <p>For older browser support, you can use this jQuery technique:</p> <pre class="lang-js prettyprint-override"><code>$(document).on('click', 'a[href^="#"]', function (event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500); }); </code></pre> <p>And here's the fiddle: <a href="http://jsfiddle.net/9SDLw/" rel="noreferrer">http://jsfiddle.net/9SDLw/</a></p> <hr> <p>If your target element does not have an ID, and you're linking to it by its <code>name</code>, use this:</p> <pre class="lang-js prettyprint-override"><code>$('a[href^="#"]').click(function () { $('html, body').animate({ scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top }, 500); return false; }); </code></pre> <hr> <p>For increased performance, you should cache that <code>$('html, body')</code> selector, so that it doesn't run <em>every single time</em> an anchor is clicked:</p> <pre class="lang-js prettyprint-override"><code>var $root = $('html, body'); $('a[href^="#"]').click(function () { $root.animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 500); return false; }); </code></pre> <hr> <p>If you want the URL to be updated, do it within the <code>animate</code> callback:</p> <pre class="lang-js prettyprint-override"><code>var $root = $('html, body'); $('a[href^="#"]').click(function() { var href = $.attr(this, 'href'); $root.animate({ scrollTop: $(href).offset().top }, 500, function () { window.location.hash = href; }); 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