简体   繁体   中英

How do I change the active nav li in separate header.html when on different pages using javascript?

I have a site with 6 pages where the header is in a separate file. I would like the nav links to be highlighted as active depending on which page I am on.

This is the main nav from the header.html:

<div id="fh5co-main-nav">
    <nav id="fh5co-nav" role="navigation">
        <ul class="nav">
            <li class="active"><a href="index.html">Home</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="products.html">Products</a></li>
            <li><a href="location.html">Location</a> </li>
            <li><a href="cafe.html">Cafe</a></li>
            <li><a href="contact.html">Contact</a></li>
        </ul>
    </nav>
</div>

It is linked in each page with this:

<div id="header"></div>

In my main.js I have this:

$(function(){
    $("#header").load("header.html"); 
    $("#footer").load("footer.html"); 
  });
$(document).ready(function() {
    // get current URL path and assign 'active' class
    var pathname = window.location.pathname;
    $('ul.nav li > a[href="/'+pathname+'"]').parent().addClass('active');
});

...but I cannot seem to figure out why it is not working. Any advice anyone could give would be greatly appreciated!!

Your anchors are relative paths ie href="contact.html" so the selector [href="/'+pathname+'"] you're using won't match any of them unless you change the value of your anchors to contain a preceding slash.

$.load accepts a callback function which allows you to execute logic after the resource is loaded inserted into the DOM.

this inside the callback is set to the DOM element which the load method was applied to ie #header .

window.location.pathname will always include the initial '/' so there is no need to prefix this in the selector.

I've also thrown in some logic to toggle active states on sibling elements.

$(function(){
  $('#header').load('header.html', function () {
    $('.nav a[href="' + window.location.pathname + '"]', this).parent().addClass('active').siblings().removeClass('active');
  }); 
  $('#footer').load('footer.html'); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM