How to Add Smooth Scrolling for Anchor Links

How To  Tutorials  Last Updated: Layers ver. 1.5 Time to Read: 2 minutes

This tutorial offers an example of how to add smooth scrolling for anchor links. There are many ways, and each one depends how your anchors are created – using Custom Anchors, or IDs, and what other widgets or scripts your site uses. You can also find Smooth Scrolling in Layers Extension bundles such as  Layers Plus.

Note: Do not use this tutorial if you have bought a child theme intended for single scrolling pages. or are using Layers Plus. Enable Smooth Scrolling in the Layers Plus options in the customizer. For child themes, please contact the author for advice on adding smooth scroll to ensure a compatible solution.

Script snippets may be added to the JavaScript panel of DevKit, or to your child theme’s theme.js file.

If you have existing scripts, be sure to add a couple blank lines with the Enter key before pasting a new snippet to avoid accidentally nesting scripts inside other script’s brackets, or make sure each $  declaration is inside the main jQuery wrapper.

Example:

 

Each jQuery snippet is setting the kind of links to look for. If you are targeting an element by its ID , for example #top  , you need to tell jQuery to look for links with hashes in them so it knows what to apply smooth scrolling to (line 3 below) and what to match it to in the HTML. Example:

This example offsets the scroll by 85 pixels via
customoffset = 85
to account for the default overlay/sticky header. If your header is taller, you must increase this value (equal to pixels). Example:

If you are using the Custom Anchor field in a widget and building menus using those anchors, you must account for the name attribute being used NOT the ID hash, as seen on line 3 below.

 

The following snippet works for most sites and allows both a back to top button and named anchors to smooth scroll. You can see it in action here on our site or on this demo.

These examples are not guaranteed to be compatible with your setup or child theme and may not work if similar scripting is already implemented that targets hashes, such as having accordions on your page. For help with custom scripting, head on over to the jQuery StackExchange or ask the Layers Community.