Reputation: 17760
Is there a method in the browser in JavaScript that I can use to navigate to an anchor on the page but NOT update the URL fragment?
For example,
HTML:
<h1 id="GettingStarted">Getting Started</h1>
JavaScript:
var anchor = "Getting Started";
window.scrollToHTMLElement(anchor);
I don't want to update the URL fragment.
URL Before:
http://www.example.com/mypage.html
URL After:
http://www.example.com/mypage.html
Upvotes: 0
Views: 44
Reputation: 309
As Jonathan Heindl points out, scrollIntoView()
can solve your problem. More specifically, you will have a element you want to go to, and a button (or whatever you want, just not an a
tag):
<h1 id="GettingStarted">Getting Started</h1>
<button type="button" id="trigger">Go</button>
Then some simple javascript code:
document.getElementById('trigger').addEventListener('click', function(){
var anchor = document.getElementById('GettingStarted');
anchor.scrollIntoView();
})
Sample result down below:
document.getElementById('trigger').addEventListener('click', function(){
var anchor = document.getElementById('GettingStarted');
anchor.scrollIntoView();
})
<h1 id="GettingStarted">Getting Started</h1>
<div style="min-height: 150vh"></div>
<button type="button" id="trigger">Go</button>
Upvotes: 1
Reputation: 1095
You can use scrollIntoView
document.getElementById('GettingStarted').scrollIntoView();
or
document.getElementById('GettingStarted').scrollIntoView({
behavior: 'smooth'
});
if you want a smooth animation.
Check out this fiddle for an example.
Upvotes: 2