Implementing Smooth Scroll with scrollToElement in JavaScript

As a web developer, I constantly strive to create seamless user experiences. One of the techniques I frequently employ is smooth scrolling to specific elements on a webpage. This can significantly enhance the usability and interactivity of a site, whether it’s navigating to a particular section, highlighting a search result, or smoothly transitioning within a single-page application.

Today, I want to share a handy function I often use, scrollToElement, which makes implementing smooth scrolling straightforward and effective. Let’s dive into how this function works and how you can utilize it in your projects.

Function Overview

The scrollToElement function scrolls to a specified element on the page. The element can be identified either by a CSS selector (string) or directly as an HTMLElement. Additionally, you can set the CSS display property of the element before scrolling to it, ensuring it is visible.

TypeScript Function Definition

Here’s the complete definition of the function in TypeScript:

/**
 * Scrolls to an element on the page
 *
 * @example
 * scrollToElement('#my-element');
 * scrollToElement(document.getElementById('my-element'));
 *
 *
 * @param el The element to scroll to (either a string or an HTMLElement)
 * @param display CSS display property to set on the element before scrolling. To remove it set to '';
 */
export const scrollToElement = (el: HTMLElement | null | string, display: string | null | undefined = 'block') => {
    let element: HTMLElement | null = null;

    if (typeof el === 'string') {
        element = document.querySelector(el) as HTMLElement | null;
    } else {
        element = el as HTMLElement;
    }

    if (!!element) {
        if (display) {
            element.style.display = display;
        }

        setTimeout(() => {
            window.scrollTo({
                top: !!element ? element.offsetTop : 0,
                behavior: 'smooth',
            });
        }, 100);
    }
};

Plain Javascript Function Definition

And the same function in plain Javascript:


function scrollToElement(el, display = 'block') {
    const element = typeof el === 'string' ? document.querySelector(el) : el;

    if (element) {
        if (display) {
            element.style.display = display;
        }

        setTimeout(() => {
            window.scrollTo({
                top: element.offsetTop,
                behavior: 'smooth',
            });
        }, 100);
    }
}

Parameter Explanation

  • el: This parameter can be either a string (CSS selector) or an HTMLElement. If it’s a string, the function uses document.querySelector to find the element. If it’s an HTMLElement, it uses it directly.
  • display: This optional parameter sets the CSS display property of the element before scrolling. By default, it’s set to 'block'. To avoid changing the display property, you can set this to an empty string ('').

How It Works

  1. Element Selection: The function first determines if el is a string or an HTMLElement. If it’s a string, it selects the element using document.querySelector. If it’s an HTMLElement, it assigns it directly.
  2. Display Property: If a display value is provided, it sets the element’s display property.
  3. Scroll to Element: The function uses setTimeout to delay the scrolling by 100 milliseconds, allowing any changes to the display property to take effect. It then uses window.scrollTo to scroll to the element’s offsetTop position with a smooth behavior.

Usage Examples

Here are some examples of how to use the scrollToElement function:

Scroll to an element using a CSS selector:

scrollToElement('#my-element');

Scroll to an element using an HTMLElement:

const myElement = document.getElementById('my-element'); scrollToElement(myElement);

Scroll to an element and change its display property:

scrollToElement('#my-element', 'flex');

Scroll to an element without changing its display property:

scrollToElement('#my-element', '');

Conclusion

The scrollToElement function is a versatile utility for scrolling to elements on a webpage. By accepting either a CSS selector or an HTMLElement, and allowing optional modification of the display property, it provides flexibility for various use cases. Incorporating smooth scrolling improves the user experience by making navigation more intuitive and visually appealing.

Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *