Navbar w/ Smooth Scrolling Same Page Links & Accessibility

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

  • Select your links.
const navbarItems = document.querySelectorAll('.navbar__list__item');
  • Loop over links & add listeners for clicks.
navbarItems.forEach(item => {
item.addEventListener('click', () => {
  • Prevent the default behaviour.
    Without this your links will jump instantly down the page ( :O no smooth, sexy scrolling! ).
event.preventDefault();
  • Select section of page related to the navbar item.
let section = document.querySelector(item.childNodes[1].getAttribute('href'));
  • Set scroll behaviour for section .
section.scrollIntoView({
behaviour: 'smooth',
block: 'start'
});
  • Set webpage focus to the clicked section .
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);
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Glyn Lewington

Glyn Lewington

More from Medium

Combine <details> and <dialog> for awesome minimal-code dropdowns

Edlink Front Page Redesign — UI Design

Working with a UX designer and optimizing my projects user flow.

Generating a LabVIEW UI 1: Wireframes

Screenshot of LabVIEW wireframe for build tab