Scroll down to to id with javascript (fixed)

im trying to get scroll down function to the specific id when click on scroll down button

<div id="first-id">
    im first id i should scroll down on first click

<div id="second-id">
    im second id i should scroll down on second click

<div id="third-id">
    im third id i should scroll down on third click

when we click on scroll down button first time it will scroll down to id=“first-id” when we again click for second time it will scroll down to id=“second-id” and when we click for third time it will scroll down to id=“third-id”.

how can we achieve this function with javascript/jquery.

i just know scroll-up to top of page and scroll down to bottom of page, i couldn’t figure out to stop on specific id on every click

<button id="scrollButton">Scroll Down</button>
<div class="srcoll-wrapper">
    <div id="section1">
        Section 1
    <div id="section2" >
        Section 2

    <div id="section3" >
        Section 3


document.addEventListener("DOMContentLoaded", function() {
    let currentSection = 1; // Initialize with the first 'id'

    const scrollButton = document.getElementById("scrollButton");

    scrollButton.addEventListener("click", function() {
        const section = document.getElementById(`section${currentSection}`);
        if (section) {
            const sectionTop = section.offsetTop;
                top: sectionTop,
                behavior: "smooth"


        if (currentSection > 3) {
            currentSection = 1; 

work fines as i wanted

1 Like

Just for fun (as I know you are sorted now) I offloaded the animation to css and allowed for the number of sections to change without changing the JS.

You might find that this scrollIntoView() example provides a little more versatility…

Full Page View

Editor View


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.