MattHeywood
MattHeywood

Reputation: 181

JQuery add class to wordpress nav menu depending on page href (not working in IE7/8)

This script adds an active class to the current page in a wordpress generated nav menu (changes color & adds small background image arrow). However the document.ready function isn't working in IE 7 & 8.

JQuery:

$(document).ready(function(){
    $('#menu-top-menu a').each(function(index) {
        if(this.href.trim() == window.location)
            $(this).addClass("active");
    });
});

CSS:

.active {color: #41A2FF !important; background-image: url('navarrow.png'); background-repeat: no-repeat; background-position: 50% 3%; padding-top: 10px;}

I've googled this a lot and looked at a number of topics on this forum relating to similar IE <9 problems, and a few answers seemed to point to the window. and .href declarations but I couldn't seem to figure out exactly why It wasn't adding the class. Any help would be appreciated as my knowledge on jquery is limited.

-Thanks

...problem solved, .trim() wasn't working in IE : if($(this).attr("href") == window.location)

Upvotes: 0

Views: 789

Answers (1)

MattHeywood
MattHeywood

Reputation: 181

To get .trim() working in ie7 & 8, if must be added in header:

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

Without using .trim():

$(document).ready(function(){
    $('#menu-top-menu a').each(function(index) {
       if($(this).attr("href") == window.location)
            $(this).addClass("active");
    });
});

...however the second method limited me to only being able to apply the class to top level navigation

Upvotes: 0

Related Questions