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.
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;
nullif 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');
}
You can use string.search or string.indexOf method in js. Here is an example code.
var url = 'http://localhost:3000/interests';
var url1 = 'http://localhost:3000/ideas';
if (url.search('interests') > -1) {
// do your work
}
or
if (url1.indexOf('ideas') > -1) {
// do your work
}
Here is your fiddle.
https://jsfiddle.net/Refatrafi/grxpmaon/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With