0

I added a function to the menu that adds an active class to various items when they are on the current page. Works well.

My question is if I can shorten the code somehow to have a clean file. So I wanted to try to reduce the two $ variables into one line, but I don't know if that's possible.

Sorry, but I'm new. The ultimate goal is to shorten the code as much as possible. Maybe if there are other ways to do this I would be curious to try them. I appreciate every answer, thanks.

This is Code

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    if(window.location.href.indexOf("/settings/") > -1) {
   $("#menu-item-1").addClass('current_menu');
   $("#menu-link-1").addClass('current_link');
}
  });
</script>

<nav>
  <ul class="nav">
    <li id="menu-item-1"><a id="menu-link-1" href="https://mywebsite.com/account/settings">Settings</a></li>
  </ul>
</nav>

this is what i try to do to shorten but it doesn't work

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    if(window.location.href.indexOf("/settings/") > -1) {
   $("#menu-item-1", "#menu-link-1").addClass('current_menu current_link');
}
  });
</script>

<nav>
  <ul class="nav">
    <li id="menu-item-1"><a id="menu-link-1" href="https://mywebsite.com/account/settings">Settings</a></li>
  </ul>
</nav>
Snorlax
  • 233
  • 8
  • 1
    Close, your comma needs to be *inside* the quotes: `$("#menu-item-1,#menu-link-1").addClass` – freedomn-m May 10 '22 at 11:18
  • With a comma outside the quotes you get two parameters, which jquery identifies as `$(selector, parent)` so, conversely, would have worked for your link if you'd done `$("#menu-link-1", "#menu-item-1")` but only for the link – freedomn-m May 10 '22 at 11:20
  • https://learn.jquery.com/using-jquery-core/selecting-elements/ – Rory McCrossan May 10 '22 at 11:23
  • @freedomn-m Thanks, it's working. However `item-menu-1` and `item-link-1` now both have the class "current_menu current_link". So I edited the css and it went fine. – Snorlax May 10 '22 at 11:28
  • Thank you for the suggestions. Is this in practice a correct way to do this? or are there more "efficient" alternatives ? – Snorlax May 10 '22 at 11:32
  • You should be able to change the styling of both menu-item and menu-link with a single css class, applied to menu-item, since menu-link is inside and can be targeted by the outer css class. – James May 10 '22 at 11:48
  • Example for above comment: css `#menu-item-1 > a { color:blue; } #menu-item-1.current > a { color:green; }` `$("#menu-item-1").addClass("current")` will also turn menu-link-1 from blue to green with no change via js to menu-link-1 – freedomn-m May 10 '22 at 12:27

0 Answers0