views:

120

answers:

2

Hi,

I'm have some issues adding a class to 2 navigation links on a theme.

I need to add a class based on a url string as i'm redirecting the page to another.

You can see the blog here: http://208.43.250.67/~thingsig/

Links are: 'Blog' and 'Keepers'

I'm using the following code:

<script type="text/javascript">
if (window.location.pathname.indexOf('/category/blog/')){
   if ( $('#nav ul li a span').text().contains('BLOG') ){
       //add class 'current_page_item' to:
       $('#nav ul li').addClass('current_page_item');
   }
}
if (window.location.pathname.indexOf('/category/keepers/')){
   if ( $('#nav ul li a span').text().contains('KEEPERS') ){
       //add class 'current_page_item' to:
       $('#nav ul li').addClass('current_page_item');
   }
}
</script>

Can anyone see why that doesnt work?

I get the following error: $ is not a function [Break on this error] if ( $('#nav ul li a span').text().contains('BLOG') ){

A: 

you should put that lines into

$(document).ready(function(){
     // here
});

Kind Regards

--Andy

jAndy
Added that and still same error,i also tried: jQuery(document).ready(function($) {but that throws this error:$("#nav ul li a span").text().contains is not a function[Break on this error] if ( $('#nav ul li a span').text().contains('BLOG') ){
Jonathon Joyce
+1  A: 

$("#nav ul li a span").text() returns a string, not a jQuery object. You cannot call contains on a string, that is the problem. Info on the text() function here.

I think you need to restructure the way you are doing your logic, $("#nav ul li a span").text() returns the following string: HomeBlogBioAboutKeepers So your contains logic will evaluate to true on every page of your site.

I think a better way to do it would be to loop through the li elements, get the text within an individual li span and then set that individual li's css when it is true.

HTH

EDIT: This works (I tried it on your site in firebug):

jQuery('#nav ul li').each(function(){
    //The comparison is case sensitive, Dont use uppercase like in your original
    if(jQuery(this).find('span').text() == "Blog"){ 
        jQuery(this).addClass('current_page_item');
    }
});
DannyLane
That helps a lot, i've changed the code to: <script type="text/javascript">jQuery(document).ready(function($) {if (window.location.pathname.indexOf('/category/blog/')){$('#nav ul li').each(function(){ if($(this).find('span').text() == "Blog"){ $(this).addClass('current_page_item'); }});}});</script>
Jonathon Joyce
However, if i'm on the home page, its display the active state for the blog AND home....I only want the blog li class to have 'current_page_item' when the url contains 'category/blog/'??
Jonathon Joyce
Ahhh i missed if (window.location.pathname.indexOf('/category/blog/') > -1)
Jonathon Joyce