Question

My menu shows the active links when clicked on it except for the home link (http://www.obsia.com). It is never highlighted. I tried playing around but I can't seem to figure it out. This is the jquery code I used to highlight the links?

 $(function(){
   var path = location.pathname.substring(1);
   if ( path )
     $('.nav a[href$="' + path + '"]').attr('class', 'active');   
 });

I also have another menu on the products pages where I would like to highlight the parents of the siblings and the our products on the global menu. This is the jquery code for the products menu:

 $(function() {
var pathname = location.pathname;
var highlight;
//highlight home
if(pathname == "")
    highlight = $('ul#accordion > li:first > a:first');
else {
    var path = pathname.substring(1);
    if (path)
        highlight = $('ul#accordion a[href$="' + path + '"]');
}highlight.attr('class', 'active');



// hide 2nd, 3rd, ... level menus
$('ul#accordion ul').hide();

// show child menu on click
$('ul#accordion > li > a.product_menu').click(function() {
    //minor improvement
    $(this).siblings('ul').toggle("slow");
    return false;
});

//open to current group (highlighted link) by show all parent ul's
$('a.active').parents('ul').show();
$('a.active').parents('h2 a').css({'color':'#ff8833'});

//if you only have a 2 level deep navigation you could
//use this instead
//$('a.selected').parents("ul").eq(0).show();

}); });

I tried adding this:

        $(this).parents('ul').addClass('active');

but that does not seem to do the trick?

Does anybody have a simple way of accomplishing it? Any help would be appreciated from you guys.

Kind Regards, G

Was it helpful?

Solution

I debugged your Javascript. The home link does not highlight because, for the home page, location.pathname is evaluated to the string "/". The variable 'path' is therefore assigned the empty string. This means that the variable 'highlight' is not assigned to.

// path is assigned the empty string
var path = location.pathname.substring(1);

// evaluating to false
if (path) {
    // we never get here
    highlight = $('ul#accordion a[href$="' + path + '"]');
}

// getting a null pointer exception
highlight.attr('class', 'active');

OTHER TIPS

In Firebug I get highlight is undefined on the line }highlight.attr('class', 'active'); looks like you might need to correct the brackets around the If statement above it?

I figured out how to get the home page link to highlight in the menu bar (That was the only link that would not highlight on the menu bar). Here is what I did:

 $(function(){
   var pathname = location.pathname;
   var path = pathname.substring(1);
    if(path == "")
        $('.nav a:first').addClass('active');
   else (path)
     $('.nav a[href$="' + path + '"]').attr('class', 'active');   
 });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top