JavaScript || How To Scroll To An Element & Add Automatic Anchor Scroll Using Vanilla JavaScript

Print Friendly, PDF & Email

The following is a module with functions that demonstrates how to scroll to a specific HTML element, as well as setting anchors to have a smooth scroll effect on button click.


1. Scroll To Element

The example below demonstrates how to scroll to a specific element.

The ‘Utils.scrollToElement‘ function accepts either a JavaScript element or a string selector of the element to scroll to.


2. Add Scroll To Anchor Target

The example below demonstrates how to automatically add a scrolling effect to an anchor target.

The ‘Utils.registerAnchorScroll‘ function gets all the anchor links on a page and registers smooth scrolling on button click using ‘Utils.scrollToElement‘.


3. Utils Namespace

The following is the Utils.js Namespace. Include this in your project to start using!


4. More Examples

Below are more examples demonstrating the use of ‘Utils.js‘. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Was this article helpful?
👍 YesNo

Leave a Reply