Navbar w/ Smooth Scrolling Same Page Links & Accessibility

Glyn Lewington
Apr 9, 2018 · 2 min read
Photo by Faye Cornish on Unsplash

Step 1 — HTML

<nav class='navbar'>
<ul class='navbar__list'>
<li class='navbar__list__item><a href='#intro'>Intro</a></li>
<li class='navbar__list__item><a href='#meatnpotatoes'>Meat 'n' Potatoes</a></li>
<li class='navbar__list__item><a href='#stuff'>Stuff</a></li>
</ul>
</nav>
<section id='intro' tabindex='0'></section>
<section id='meatnpotatoes' tabindex='0'></section>
<section id='stuff' tabindex='0'></section>

Step 2 — Javascript

const navbarItems = document.querySelectorAll('.navbar__list__item');
navbarItems.forEach(item => {
item.addEventListener('click', () => {
event.preventDefault();
let section = document.querySelector(item.childNodes[1].getAttribute('href'));
section.scrollIntoView({
behaviour: 'smooth',
block: 'start'
});
setTimeout(() => section.focus(), 500);
const navbarItems = document.querySelectorAll('.navbar__list__item');navbarItems.forEach(item => {
item.addEventListener('click', () => {
event.preventDefault();
let section = document.querySelector(item.childNodes[1].getAttribute('href'));
section.scrollIntoView({
behaviour: 'smooth',
block: 'start'
});
setTimeout(() => section.focus(), 500);
}
}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade