Aileen Bea
Aileen Bea

Reputation: 35

Bootstrap 3.3.1 - Highlight Current Navigation Menu Item

The script that I use currently works well actually, as long as I keep my file structure like this:

http://website.com/
http://website.com/page1.php
http://website.com/page2.php
http://website.com/page3.php

but when I impliment my mod_rewrite code to take away the ".php"

http://website.com/
http://website.com/page1
http://website.com/page2
http://website.com/page3

my navigation highlight script stops working.

Here is how I implement my code

The HTML

<body id="page1">

The JS

$(function() {

    //highlight the current nav
    //each of the following lines represents a different page
    $("#page1 a:contains('Page 1')").parent().addClass('active');
    $("#page2 a:contains('Page 2')").parent().addClass('active');



});

The ID within the JS looks for the ID within each body tag, and the part that says ('Page 1') looks for the item within the menu to identify which menu item to highlight. As I said, it works fine, until take away the .php. I'm assuming it has something to do with .parent within the js, but I'm not sure what to replace it with, or how to make it work right. Any suggestions?

Upvotes: 2

Views: 2246

Answers (1)

Ramiz Wachtler
Ramiz Wachtler

Reputation: 5683

If the <body> tag in each of your pages, contains an unique ID, you could just check if this id is existing.

Like this (UPDATED):

for(var i = 0; i < $(".menu-item").length; i++){
    var item = i+1;
    if($("#page"+item).length>0){
        $("li:nth-child("+item+")").addClass("active");
        break;
    }
}

UPDATE Your updated fiddle

Fiddle

Upvotes: 1

Related Questions