Ben393 Ben393 - 3 months ago 21
CSS Question

If window.location.href does not match a certain string, add css class to element

I am new to javascript/jQuery and am trying to add a css class to an element if the page's url does not match one of three strings. I cannot these lines of my code to work.

if (window.location.href.match(/(interests|ideas|art)/) > -1) {
jQuery("#nav-about").addClass('active');
}


Any ideas? Is my syntax incorrect?

EDIT:

It seems like the answers everyone has given me should be working, but they aren't. Maybe other lines of my code are conflicting:

$(document).ready(function() {
if (window.location.href.search(/(interests|ideas|art)/) > -1) {
jQuery("#nav-about").addClass('active');
}
if (window.location.href.match(/(interests)/) != null) {
jQuery("#nav-interests").addClass('active');
}
if (window.location.href.match(/(ideas)/) != null) {
jQuery("#nav-ideas").addClass('active');
}
if (window.location.href.match(/(art)/) != null) {
jQuery("#nav-art").addClass('active');
}
});


My site is benxd.me. The link,
#nav-about
on this main page is what needs the class
active
; the script does not work on this page. The script on the other pages, interests, ideas and photography work.

Answer

For what you are doing, you want to use .search() not .match(). The return value for .search() is the index of the first match, or -1 if there is not a match. The return value for .match() is:

An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.

Fixing the above issue, and given that you have stated you want to add the class when the URL does not match, the code should be:

if (window.location.href.search(/(interests|ideas|art)/) === -1) {
    jQuery("#nav-about").addClass('active');
}
Comments