\n\n\nThis approach loads the navigation bar into each page using JavaScript's fetch. Helping us to park the navigation into a contained, clean, and easy-to-maintain corner; a fine example of DRY (Don't Repeat Yourself).","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Alex Kataev","url":"https://explain.codes//author/alex-kataev"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2024-12-20T18:00:01.232Z","dateModified":"2024-12-20T18:00:03.024Z"}
Explain Codes LogoExplain Codes Logo

How can I reuse a navigation bar on multiple pages?

javascript
responsive-design
performance
best-practices
Alex KataevbyAlex Kataev·Dec 20, 2024
TLDR

Easily reuse your navigation bar using JavaScript:

<!-- Navigation.html - Here's where your cool nav lives --> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </nav>
// Include this script after a cup of coffee fetch('navigation.html') .then(res => res.text()) .then(nav => document.getElementById('navbar').innerHTML = nav);
<!-- Add this to each page, like sprinkles on a cupcake --> <div id="navbar"></div> <script src="script.js"></script>

This approach loads the navigation bar into each page using JavaScript's fetch. Helping us to park the navigation into a contained, clean, and easy-to-maintain corner; a fine example of DRY (Don't Repeat Yourself).

Using jQuery for loading navigation

If jQuery is your poison of choice, grab the magic incantation as shown:

$(document).ready(function(){ $("#navbar").load("navigation.html"); });

You need to call the jQuery bouncer at the door:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <div id="navbar"></div>

Simplified syntax and wielding power over potential cross-browser demons make jQuery a formidable alternative to fetch.

PHP in the mix

PHP, a stalwart server-side language, offers a neat trick to reuse HTML through the mystical include:

<?php include 'navigation.php'; ?>

It injects your navigation bar HTML wherever the server lays down the page floorplan, creating a central hub for your navigation code, minus the AJAX or Fetch on the client side.

NOTE: Make sure your navigation is hanging out in a .php file and your server is PHP friendly.

Highlighting active page

Elevate navigation bars by illuminating the active page:

window.onload = function () { const links = document.querySelectorAll('nav ul li a'); const currentUrl = window.location.href; // Time for a spotlight on the actor! links.forEach(function(link) { if (link.href === currentUrl) { link.className = "active"; } }); };

Fashionably attired with CSS:

a.active { font-weight: bold; color: red; }

This little spectacle will brighten the active link, adding a dash of flair to your navigation experience.

Cleaning up and performance

Maintaining a clean and efficient code for a navigation bar cuts both ways — making life easier for future maintenance and potentially boosting overall performance. Keep the HTML clutter-free, CSS lean, and let the good times roll.

Bear in mind, jQuery's load method, although handy, can run slower than the vanilla JavaScript's fetch due to some extra overhead for the jQuery library.

Frameworks to the rescue

Front-end frameworks, say Angular, React, or Vue.js, bring their own game plan for developing reusable components. For instance, React uses JSX to render components, ensuring they are reused across multiple pages:

import React from 'react'; import NavigationBar from './components/NavigationBar'; function App() { return ( <div> <NavigationBar /> {/* Rest of the party */} </div> ); }

Such an approach paves the way for component-based architecture while catering to the need for state management, quite handy when you've a demanding navigation bar.