How can I reuse a navigation bar on multiple pages?

blackRob4953 picture blackRob4953 · Aug 12, 2015 · Viewed 174.6k times · Source

I just finished making my home/index.html page. To keep the nav bar where it is, and have it stay while users click through all my pages. Do I have to copy and paste the nav code to the top of each page? Or is there another way to do so that would look cleaner?

HMTL nav:

<nav>
    <div>
        <a href="/">
            <div id="logo"><img src="image.png" alt="Home"/></div>
            <div id="headtag"><img src="image.png" alt="Home"/></div>
            <div id="tagline"><img src="image.png" alt="Home"/></div>
        </a>
    </div>
    <div> 
        <a href="/" class="here">Home</a>
        <a href="/about.html" >About</a>      
        <a href="/services.html" >Services</a>          
        <a href="/pricing.html" >Pricing</a>    
        <a href="/contact.html" >Contact Us</a>
        <input id="srchbar" type="search" placeholder="Search">
    </div>
</nav>

Answer

Ramtin picture Ramtin · Feb 19, 2017

This is what helped me. My navigation bar is in the body tag. Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar). In the target page, this goes in the head tag:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

Then in the body tag, a container is made with an unique id and a javascript block to load the nav.html into the container, as follows:

<!--Navigation bar-->
<div id="nav-placeholder">

</div>

<script>
$(function(){
  $("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->