SolarWind SolarWind - 2 months ago 9
CSS Question

How to load nav menu from an external file? (No Wamp, all code must be 'browser-side')

I have a static HTML web site. I want to store the the nav (top) menu in an external file so when I change the menu, I want to see the change in all pages.

I REALLY REALLY NEED to be able to see the web pages also locally (regular Windows user without the need to install additional software: Apache, PHP, Wamp, specific browsers, etc).

There are two similar StackOverflow questions that partially solves this issue using PHP, SSIand ... frames. None of the solutions is good for me:


  • Frames out of discussion obviously (bad from SEO POV and also obsolete in HTML5).

  • PHP and SSI will only work after the site was uploaded on the server so it won't work locally.



The solution I see is putting ALL the menu in an external JS file. However, all the JS examples I fave found still have some 'parts' of the menu in the HTML file.

So, it is possible to have all menu in a JS file and only a call (and no actual menu items) to that file in my HTML files? I only have basic knowledge of JS. But enough to adapt a generic example for my needs.

Answer

menu.html

<ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="active1.html">Contact</a></li>
    <li><a href="active2.html">About</a></li>
    <li><a href="active3.html">Portfolio</a></li>
</ul>

index.html

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<div id="nav"></div>

js file:

$(function() {

    $("#nav").load("menu.html");

    function activeNav() {
        var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
         $("#nav ul li a").each(function(){
              if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
              $(this).addClass("active");
         });
    }

    setTimeout(function() {
        activeNav();
    }, 100);

});

The setTimeout lets the page load and then runs the function to see what link is active and then you can add a class in the css:

#nav ul li a.active {
        color: #ff0000;
        font-weight: bold;
    }
Comments