Don't want to add anchor href to the url when scroll button clicked

Viewed 225

I am building a single-page website, it will have a landing page and a main page where the user will do some computation. In the landing page, there is a button for scrolling smoothly to the main page. While I was researching how to make this scrolling stuff, I've found that CSS property called scroll-behaviour used with anchors.

What I don't like about this approach is when I clicked the anchor button, the id of the scrolled div is appended to the URL. See below snipped:

* {
    margin: 0;
    padding: 0;
}

html {
    scroll-behavior: smooth;
}

#landing-page {
    background-color: bisque;
    height: 100vh;
}

#main-page {
    background-color: yellow;
    height: 100vh;
}
<div id="container">
    <div id="landing-page">
        <h1>Landing Page</h1>
        <a href="#main-page">Go to main page</a>
    </div>
    <div id="main-page">
        <h1>Main Page</h1>
    </div>
</div>

When I clicked the button, it scrolls to the correct viewport but URL becomes localhost:1234/#main-page from localhost:1234. As may it sounds unnecessary concern, I really want to prevent this. Is there anything I can do, or maybe should I change the scrolling approach altogether(not using anchors)?

1 Answers

Yes, if you don't want the URL to change, you have to scroll to the element using javascript. Something like:

document.getElementById("anchorElement").addEventListener("click", e => {
    document.getElementById("main-page").scrollIntoView();
})
* {
    margin: 0;
    padding: 0;
}

html {
    scroll-behavior: smooth;
}

#anchorElement {
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}

#landing-page {
    background-color: bisque;
    height: 100vh;
}

#main-page {
    background-color: yellow;
    height: 100vh;
}
<div id="container">
    <div id="landing-page">
        <h1>Landing Page</h1>
        <span id="anchorElement">Go to main page</span>
    </div>
    <div id="main-page">
        <h1>Main Page</h1>
    </div>
</div>

Related