<a href="#sectiona">Go to Section A</a> <a href="#sectionb">Go to Section B</a>
<p>Smooth Scrolling HTML Bookmark Links using ES6 JavaScript and the updated version of <code>element.scrollIntoView()</code> method.</p>
<p>The browser's URL is updated each time with a new hash.</p>
<div style="height:400px"></div>
<div id="sectiona">This is section A</div>
<div style="height:100px"></div>
<div id="sectionb">This is section B</div>
a{
font-size: 120%;
margin-right: 100px;
}
#sectiona, #sectionb{
font-size: 140%;
font-weight: bold;
text-align: center;
padding: 20px;
background: pink;
width: 50%;
height: 150px;
}
#sectionb{
background: purple;
color: white;
}
let anchorlinks = document.querySelectorAll('a[href^="#"]')
for (let item of anchorlinks) { // relitere
item.addEventListener('click', (e)=> {
let hashval = item.getAttribute('href')
let target = document.querySelector(hashval)
target.scrollIntoView({
behavior: 'smooth'
})
history.pushState(null, null, hashval)
e.preventDefault()
})
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.