Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 550
Ben393 Avatar asked Jun 30 '26 12:06

Ben393


2 Answers

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');
}
like image 154
Makyen Avatar answered Jul 02 '26 02:07

Makyen


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/

like image 43
Rafi Ud Daula Refat Avatar answered Jul 02 '26 01:07

Rafi Ud Daula Refat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!