Smooth Scrolling For Mouse Wheel & Anchor Links – smooth-scroll.js

Category: Animation , Javascript | July 1, 2024
Author:66HEX
Views Total:390 views
Official Page:Go to website
Last Update:July 1, 2024
License:MIT

Preview:

Smooth Scrolling For Mouse Wheel & Anchor Links – smooth-scroll.js

Description:

smooth-scroll.js is a small JavaScript library that enables configurable smooth-scrolling effects on the mouse wheel and anchor links within your document.

How it works:

  • Initialization: The code starts by creating a new SmoothScroll object and sets up event listeners for mouse wheel interactions on the specified target element. It also ensures cross-browser compatibility for document scrolling.
  • Scroll Event Handling: When a user scrolls with the mouse wheel, the scrolled function is triggered. This function prevents default scrolling behavior and calculates the scroll delta based on the browser’s specific wheel event properties.
  • Smooth Scrolling Animation: The update function is called to handle the core animation logic. It calculates the difference between the desired scroll position and the current scroll position and gradually adjusts the scroll top value using requestAnimationFrame for a smooth animation.
  • Link Click Handling: The code identifies anchor links within a navigation element (nav) and prevents their default behavior when clicked. It then extracts the target element’s ID from the clicked link and calls the scrollTo method on the SmoothScroll object to initiate a smooth scroll animation to that specific element.
  • scrollTo Method: This method calculates the target position based on the clicked link and the current scroll position. It then uses a similar animation loop as the update function to smoothly scroll the target element into view.

How to use it:

1. Download and load the “smooth-scroll.js” script into your HTML file. Remember to replace “path/to/smooth-scroll.js” with the actual path to the library file.

<script src="path/to/smooth-scroll.js"></script>

2. Create a new instance of the SmoothScroll object and link it to your document (or any container you specify):

new SmoothScroll(document);

3. If you desire to adjust the scrolling animation, you can pass additional parameters to the SmoothScroll function during instantiation. These parameters control the scrolling speed and smoothness.

new SmoothScroll(document, speed, smooth);

You Might Be Interested In:


Leave a Reply