3

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)?

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Cagri Uysal
  • 255
  • 3
  • 11
  • 2
    What you are describing has nothing to do with `scroll-behavior`. You are simply using named anchors and named anchors take you to a named portion of the document. The change in the URL is not something you can avoid. If you want this behavior and no change to the URL, you'll need to implement the scrolling behavior with JavaScript. – Scott Marcus Aug 16 '20 at 22:31
  • @ScottMarcus, so is there any other way to achieve this smooth scrolling other than using anchors. – Cagri Uysal Aug 16 '20 at 22:34
  • 1
    Yes, as I said, through the use of a JavaScript implementation. – Scott Marcus Aug 16 '20 at 22:38
  • 1
    See this post here: https://stackoverflow.com/questions/15223006/scroll-with-anchor-without-in-url – Nathaniel Flick Aug 16 '20 at 22:38

1 Answers1

1

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>
JayCodist
  • 2,424
  • 2
  • 12
  • 28