tags:

views:

63

answers:

3

Basically the idea is to find out what the current location is of the document and change the class of the link (navigation accordion) to be changed. So far I have this below it works if the pageURL (variable) is the actual link but I do not want to create a whole list of possible links hence the $(location).att('href');

$(document).ready(function() {
    var pageURL = $(location).attr('href');
    $('a[href=pageURL]').attr('class', 'active');
});

Any help from any one would be greatly appreciated

Thanks in advance

+4  A: 

You need to concatenate the variable into the selector string.

$('a[href=' + pageURL + ']').attr('class', 'active'); });

The way you had it, "pageURL" was simply part of the selector, so jQuery was looking for <a> elements with "pageURL" for the href attribute.

Also, I don't know what the location variable represents, but if you're looking for the current window location, you need a different approach.

patrick dw
thank you patrick I am currently using the variable as the links at the moment may need the entire path (http://) which the window.location in javascript fails to put into it
NWhite
@NWhite - I thought `window.location` gave you the `http://` in all browsers. Anyway, if not, just test for it and append it if necessary. I'll update my answer.
patrick dw
sorry my fault window.location does I was using location.pathname from Slaks answer oops
NWhite
@NWhite: You should use `[href*=...]`.
SLaks
ah ok sorry I didn't notice the * in your answer thanks SLaks as well
NWhite
+3  A: 

By writing 'a[href=pageURL]', you are searching for a elements with href attributes equal to the literal pageURL, not the contents of the variable.
Instead, you need to concatenate the contents of the variable into the selector string.

For example:

$('a[href*="' + location.pathname + '"]').attr('class', 'active');

There's no point in using jQuery to access location.href.
Writing location.pathname will make it work even if the link doesn't include a domain name.
Using the [href*=...] selector matches elements with href attributes that contain the string.

SLaks
Just like `/foo/bar` contains `/foo`.
Gumbo
@Gumbo: If that is an issue, you can change it to `href$=`, which checks that it ends with that path. However, that won't handle querystrings.
SLaks
+2  A: 

The correct syntax is:

$('a[href=' + pageURL + ']').attr('class', 'active'); });