The following is my html source code structure.
Products
software.html
hardware.html
index.html
main-navbar.html
scripts
load-main-nav.js
I have moved my main navigation bar to a seperate file because it repeats in every page and am using javascript to load it into the respective pages. I have an empty div in the pages where I want to load the navbar.
<div id="main-nav"></div>
I have managed to load the navbar using jscript into the index.html page. But when I click the Software link it goes to the respective page but does not show the navigation bar. When I changed the javascript to $("#main-nav").load("../main-nav.html"); it displays the navbar for the Software page but not the index.html. Is there a way I could change the location part so that I can use the same script for files in any folders in my project?
main-navbar.html
<nav class="navbar navbar-default mc-header navbar-static-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mc-collapse-nav">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="../index.html"><img id="logo" src="images/logo.svg" alt="Company Logo"></a>
</div>
<div id="mc-collapse-nav" class="collapse navbar-collapse mc-navbar-spacing">
<ul class="nav navbar-nav navbar-right" >
<li><a href="Products/software.html">Software</a></li>
<li><a href="Products/hardware.html">Hardware</a></li>
</ul>
</div>
</nav>
load-main-nav.js
$(function(){
$("#main-nav").load("main-nav.html");
});
I was able to accomplish this (without having to use php) by placing
<base href="../">
in the software.html & hardware.html header. Once you do this, you will have to make sure you update all the links in software.html & hardware.html as if they are being accessed from your top folder. I would also just put the js in each of those files so that it looks like the following.
<!--Navigation bar-->
<div id="main-nav"></div>
<script>
$(function () {
$("#main-nav").load("main-navbar.html");
});
</script>
<!--end of Navigation bar-->
There has been some good discussion on the uses of the base tag in this thread:
What are the recommendations for html <base> tag?
Every site is different and while I was able to use this method on one of my sites, I was not able to use it effectively in another website (I couldn't use it on a site that required smooth transitions between local hash URLS).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With