logo dile-components dile-components

DileSmoothScroll

This Mixin includes all methods related to scroll the entire document area. These are:

For a plain <a href="#section"> you don't need this mixin at all — add scroll-behavior: smooth to your CSS (ideally inside @media (prefers-reduced-motion: no-preference) so it respects that accessibility setting) and the browser animates the jump natively, with no JavaScript. This mixin is for triggering a scroll programmatically from your component's own code instead — after a button click, a form validation error, or as part of other logic.

Installation

npm install @dile/utils

Usage

To use the mixin in a Web Component you need to extend your component with the mixin:

import { DileSmoothScroll } from '@dile/utils/mixins/smooth-scroll';

class MyOwnComponent extends DileSmoothScroll(LitElement) {
  // code of your own component
}

Methods

smoothScrollToTop()

Scrolls the document to the top of the page with a smooth animation.

Parameters: None

Example:

const component = document.querySelector('my-component');
component.smoothScrollToTop();

smoothScrollToBottom()

Scrolls the document to the bottom of the page with a smooth animation.

Parameters: None

Example:

const component = document.querySelector('my-component');
component.smoothScrollToBottom();

smoothScroll(top, left)

Scrolls the document to a specific position with a smooth animation.

Parameters:

Example:

const component = document.querySelector('my-component');
// Scroll to 500px from top and 100px from left
component.smoothScroll(500, 100);

smoothScrollBy(top, left)

Scrolls the document by a relative amount (from the current position) with a smooth animation.

Parameters:

Example:

const component = document.querySelector('my-component');
// Scroll down 300px
component.smoothScrollBy(300, 0);
// Scroll up 200px
component.smoothScrollBy(-200, 0);

smoothScrollElementIntoView(element)

Scrolls an element into the viewport with a smooth animation.

Parameters:

Example:

const component = document.querySelector('my-component');
const targetElement = document.getElementById('my-target');
component.smoothScrollElementIntoView(targetElement);