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>   

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

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

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>
    
    <div id="section2" >
        Section 2
    </div>

    <div id="section3" >
        Section 3
    </div>
</div>

js

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;
            window.scrollTo({
                top: sectionTop,
                behavior: "smooth"
            });
        }

        currentSection++;

        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
https://codepen.io/Snady_Leiby/full/oNQRoyv

Editor View
https://codepen.io/Snady_Leiby/pen/oNQRoyv

2 Likes

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