Oliver Angelil Oliver Angelil - 3 months ago 10x
Javascript Question

Including a common html header in all pages in website of 20 pages (with active class)

Assume I have 20 navbar items, each one linking to a different page on my website. And on each page those 20 items remain the same. To avoid copy-pasting across all .html files, other solutions have suggested doing this with php. But how would I make the active menu item lit white for example? I want to refrain from copy-pasting the header across to all the .html files, because if I want to add one more navbar item, I will have to manually add it to all .html files.

There must be a simple solution with an active item for the active page.


Naomik, your javascript solution looks most promising, although I currently can't get it to work (see second edit below).

My navbar is defined in nav.html:

<nav id="nav" class="navbar navbar-inverse">
<ul id="navigation" class="nav navbar-nav navbar-left">
<li class="active"><a href="about.html" >About</a></li>
<li><a href="services.html" >Services</a></li>
<li><a href="pricing.html" >Pricing</a></li>

And this is one of the three html pages (about.html). I use JS to load in the nav.html file. The JS snippet before the closing body tag is the one provided by naomik.

<!DOCTYPE html>
<html lang="en">
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
$.get("nav.html", function(data){
<!-- *** NAVBAR *** -->
<div id="nav-placeholder"></div>
<!-- *** MAIN TEXT *** -->
function removeQueryString(url) {
return url.split('?')[0]
[].forEach.call(document.querySelectorAll('a'), function(elem) {
if (removeQueryString(elem.href) === removeQueryString(window.location.href))

Although Naomik's solution leads to a flashing website on every load of a page. I have therefore applied Relisora's solution.



You first want to give each of your 20 pages a name ( or a number ).

On each page, write the page name

<?php $page_name = "index" ?>

Then you import your navbar

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

Now in your navbar.php you want to check on what $page_name you are

<?php if ($page_name == 'index') {echo ' id="active"';} ?>

And you do that for each page you have.

Now you'll just want to have #active {} in your CSS to determine the style, and your current page will show with active style.