Reputation: 225
How can I add a conditional statement that says something like
if(window.location.href.indexOf("#/brandpartners"))
{
$("#brandpartners").addClass("specialbrand");
}
The hash seems to break the statement. Is there a better way?
Upvotes: 2
Views: 6699
Reputation: 150000
indexOf()
returns -1 if the string is not found, which evaluates as "truthy" such that your if
statement isn't doing what you think it is. So try:
if (window.location.href.indexOf("#/brandpartners") != -1) {}
Upvotes: 1
Reputation: 707148
First of all, you can't use indexOf that way. It returns -1, when it's not found which isn't false.
It makes a lot more sense to me to just use the built-in parsing of the hash value in the location object. I'd suggest doing it this way:
if (window.location.hash == "#brandpartners") {
$("#brandpartners").addClass("specialbrand");
}
I don't know your URL structure, but there shouldn't be a need for a slash after the # for a simple hash value. But, if you insist on using the slash, it would look like this:
if (window.location.hash == "#/brandpartners") {
$("#brandpartners").addClass("specialbrand");
}
Upvotes: 9
Reputation: 24053
As @jfriend00 sais, it should be:
if(window.location.href.indexOf("#/brandpartners")!=-1)
{
$("#brandpartners").addClass("specialbrand");
}
Upvotes: 1
Reputation: 41209
The hash (#
) isn't breaking the statement at all for me. But I don't know exactly why you have the /
in there when you don't need it.
var str = "http://stackoverflow.com/questions/6950161#hmenus";
alert(str.indexOf("#hmenus"));
This code alerts 42, which means it should do what you want. I
Upvotes: 1