<header>
<ul>
<li>
<a href="#section1">section 1</a>
</li>
<li>
<a href="#section2">section 2</a>
</li>
<li>
<a href="#section3">section 3</a>
</li>
<li>
<a href="#section4">section 4</a>
</li>
<li>
<a href="#section5">section 5</a>
</li>
</ul>
</header>
<section id="section1" class="section1">
<h2>section 1</h2>
</section>
<section id="section2" class="section2">
<h2>section 2</h2>
</section>
<section id="section3" class="section3">
<h2>section 3</h2>
</section>
<section id="section4" class="section4">
<h2>section 4</h2>
</section>
<section id="section5" class="section5">
<h2>section 5</h2>
</section>
body{
padding-top: 70px;
margin: 0;
}
header{
background: blue;
padding: 10px;
position: fixed;
top: 0;
left: 0;
right: 0;
}
header ul{
display: flex;
justify-content: center;
gap: 10px;
}
header ul li{
list-style-type: none;
}
header ul li a{
color: #fff;
}
section{
padding: 15px 30px 300px;
margin: 30px 0;
color: #fff;
}
.section1{
background: red;
}
.section1{
background: red;
}
.section2{
background: darkgreen;
}
.section3{
background: firebrick;
}
.section4{
background: navy;
}
.section5{
background: goldenrod;
}
document.addEventListener('DOMContentLoaded', function() {
// Moving to anchor on page load
scrollToAnchor();
// Move to anchor when clicking on anchored links
const headerLinks = document.querySelectorAll('a[href*="#"]');
headerLinks.forEach(function(link) {
link.addEventListener('click', function(event) {
if(event.target.pathname === window.location.pathname){
event.preventDefault();
let hash = this.getAttribute('href').split('#')[1];
scrollToAnchor('#' + hash);
}
});
});
});
function scrollToAnchor(hash = window.location.hash) {
if(hash.length > 1){
let headerHeight = document.querySelector('header').offsetHeight,
targetElement = document.querySelector(hash);
if(targetElement) {
var targetOffset = targetElement.offsetTop - headerHeight;
window.scrollTo({
top: targetOffset,
behavior: 'smooth'
});
}
}
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.