Highlight a button based on location

I am trying to highlight the navigation button (in the menu) based on the page being viewed. Here is what I still have:

var loca = String(document.location.href);

// Get document location and specific page.
if (loca) {
    if(loca.search(RegExp("((/[\w]*)\.php)")) != -1) {
        activate(loca.match(RegExp("((/[\w]*)\.php)").split("/").join("")));
    } else {
        activate("home");
    }
}

// Activate a button
function activate(bName) {
    $(".button[name=" + bName + "]").css({
        "border-left": "1px solid white",
        "border-right": "1px solid white"
    });
}

I want this to happen:

  • Get page URL
  • Get a specific page file name, and if it is not found, then we are on the main page.
  • Using jQuery, I try to find the name of the button, and if the name matches the file name, highlight it.

The thing is, it only emphasizes the Home button. What am I doing wrong? Also, if you have any suggestions on how I can do this, let me know!

+1
source share
5 answers

I would get the file name as follows:

var pathname = window.location.pathname.split("/");
var filename = pathname[pathname.length-1].split(".")[0];

alert(filename);
+2
source

Your regular expression is incorrect.

var loc_match = window.location.href.match(/(\w+)\.php/);
activate(loc_match ? loc_match[1] : "home");
+1

, , . console.log?

0

- . :

var currentPage = window.location.pathname.toLowerCase().split('/').reverse()[0].split('#')[0].split('?')[0];

if (!currentPage || currentPage == '')
{
    currentPage = 'default.aspx';
}

$('#nav li').removeClass('current').each(function() {
    var href = $(this).find('a').first().attr('href');
    if (href && href.toLowerCase().indexOf(currentPage) >= 0)
    {
        $(this).addClass('current');
    }   
});

URL-. reverse() , , , .

0

RegExp, ( , var a = /\w/i;); , reg exp:

var loca = document.location.href;
var pattern = new RegExp("[\\w]*(?=\\.php)","i");
// Get document location and specific page.
    if(pattern.test(loca)) {
        activate(pattern.exec(loca));
    } else {
        activate("home");
    }
// Activate a button
function activate(bName) {
    $(".button[name=" + bName + "]").addClass('active')
}

And as already mentioned, it is easier to assign a class to the active element.

0
source

All Articles