MacKenzie Software

Reuse navigation bar on multiple pages

Posted by MacKenzie Software on June 18, 2020

When building websites it's common that you may want to reuse a fragment of a page on multiple HTML pages, for example the header or footer section of a page.

There are many ways of doing this - you could build a single page application for example and only switch in the main content you need. In most cases that is overkill however. The simplest way to do this is as follows..

In your head section in your main file (e.g. your index.html), bring in jquery.

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

Then in your body, create a div with an ID which you can reference. In my case, it's nav-placeholder.

<body>
    <div id="nav-placeholder">
    </div>
</body>

And then, still within the body tag, you want to add a function to load another file which contains the HTML that you want to render on mulitple pages. In my case, it's the navigation pane.

<script>
    $.get("navigation.html", function(data){
        $("#nav-placeholder").replaceWith(data);
    });
</script> 

And it's as easy as that. The full code you would need would be:

index.html

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> 
</head>
<body>
    <div id="nav-placeholder"></div>
    <script>
        $.get("navigation.html", function(data){
            $("#nav-placeholder").replaceWith(data);
        });
    </script> 
    <p>My main page code</p>
</body>
</html>

navigation.html

<p>My navigation code!</p>

You can checkout this code on github.