GatsbyJS Plugin: Smoothscroll with Offset
- Published on
- -1 min read
I've been using the gatsby-plugin-smoothscroll plugin in the majority of GatsbyJS builds to provide a nice smooth scrolling effect to a HTML element on a page. Unfortunately, it lacked the capability of providing an offset scroll to position, which is useful when a site has a fixed header or navigation.
I decided to take the gatsby-plugin-smoothscroll
plugin and simplify it so that it would not require a dependency on polyfilled smooth scrolling as this is native to most modern browsers. The plugin just contains a helper function that can be added to any onClick
event with or without an offset parameter.
Usage
The plugin contains a smoothScrollTo
helper function that can be imported onto the page:
// This could be in your `pages/index.js` file.
import smoothScrollTo from "gatsby-plugin-smoothscroll-offset";
The smoothScrollTo
function can then be used within an onClick
event handler:
<!-- Without offset -->
<button onClick={() => smoothScrollTo("#some-id")}>My link without offset</button>
<!-- With offset of 80px -->
<button onClick={() => smoothScrollTo("#some-id", 80)}>My link with offset</button>
Demo
A demonstration of the plugin in use can be found by navigating to my Blog Archive page and clicking on any of the category links.
Prior to this plugin, the category list header would be covered by the sticky navigation.
Now that an offset of 80px can be set, the category list header is now visible.
Links
Before you go...
If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!
Leave A Comment
If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.