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)?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.