Adding selected state to navigation with window location match
I know that others have asked about adding a class to a navigation based on window.location, but I couldn't quite fit my question within those bounds, so hopefully it's alright to ask here.
Requirement
Add a class based on window location
Complexity
The current if/else method I have doesn't work correctly, because all subsequent URLs will have the initial word we're looking for,
and I'd like to have the final else to be on nav id#3 - (because the url's there will all be varied and may change later so adding those specifically in the if/else seems redundant)
So far I've probably explained nothing, so here's what the code looks like:
- if (window.location.pathname.match(/(employees)/)) {
- $('#nav1').addClass("selected");
- }
- if (window.location.pathname.match(/(why-us)/)) {
- $('#nav2').addClass("selected");
- }
- if (window.location.pathname.match(/(enroll)/)) {
- $('#nav4').addClass("selected");
- }
- if (window.location.pathname.match(/(support)/)) {
- $('#nav5').addClass("selected");
- }
- else {
- $('#nav3').addClass("selected");
- }
- document.write(window.location.pathname)
The problem with this is that all the subsequent urls have employees as part of the URL, so you end up with both the "home" navigation selected, in addition to the current location that you're in. Now ideally I think what may be best is to use a switch/case so that once a match is found, you break out. Something similar to the following I was tinkering with, but I'm not quite sure how to implement:
- switch (newPath){
- case window.location.pathname.match(/(employees)/)):
- $('#nav1').addClass("selected");
- break;
-
- case (window.location.pathname.match(/(why-us)/)):
- $('#nav2').addClass("selected");
- break;
-
- case (window.location.pathname.match(/(enroll)/)):
- $('#nav4').addClass("selected");
- break;
-
- case (window.location.pathname.match(/(support)/)):
- $('#nav5').addClass("selected");
- break;
-
- default:
- $('#nav3').addClass("selected");
Any help would be greatly appreciated.