skip to Main Content

Smooth Scroll Only Works Once:
The first anchor link works fine, but after that, subsequent links cause the page to jump instead of scrolling smoothly.

I’m trying to implement smooth scrolling on my webpage so that when a user clicks on an anchor link, the page scrolls smoothly to the target section instead of jumping instantly

2

Answers


  1. Maybe you don’t need JS there is already a ready-made CSS solution

    html {
      scroll-behavior: smooth;
    }
    
    Login or Signup to reply.
  2. <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Smooth Scroll</title>
        <style>
            section {
                height: 100vh;
                padding: 20px;
                border: 1px solid #ddd;
            }
        </style>
    </head>
    <body>
        <nav>
            <a href="#section1">Go to Section 1</a>
            <a href="#section2">Go to Section 2</a>
            <a href="#section3">Go to Section 3</a>
        </nav>
    
        <section id="section1">Section 1</section>
        <section id="section2">Section 2</section>
        <section id="section3">Section 3</section>
    
        <script>
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    const targetId = this.getAttribute('href');
                    const targetElement = document.querySelector(targetId);
                    targetElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start' // Optional: scrolls to the start of the element
                    });
                });
            });
        </script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search