1

Here is my HTML that shows the sidebar menu:

 <div class="sidebar"> <a class="active" href="<website>/humrec.php">HR Homepage</a> <a href="<website>/hrbenefits.php">Benefits Information</a> <a href="#contact">Scheduling</a> <a href="#about">Links</a> </div> 

Here is the jQuery code I have, still not working though:

 $(document).ready(function(){ $(".sidebar a").click(function ( e ) { e.preventDefault(); $(".sidebar a.active").removeClass("active"); //Remove any "active" class $("a", this).addClass("active"); //Add "active" class to selected tab // $(activeTab).show(); //Fade in the active content }); }); 
1
  • $("a", this) looking for anchors inside of the anchor Commented Mar 19, 2020 at 15:21

1 Answer 1

1

You logic is almost correct, however the issue is $("a", this). That selector is looking for an a element within this. The problem is that this is the a which was just clicked, so you're looking for an a within an a, which doesn't match the HTML structure you've got.

To fix the problem you just need to use $(this) to reference the a which was clicked:

jQuery(function($) { $(".sidebar a").click(function(e) { e.preventDefault(); $(".sidebar a.active").removeClass("active"); $(this).addClass("active"); }); });
.active { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="sidebar"> <a class="active" href="<website>/humrec.php">HR Homepage</a> <a href="<website>/hrbenefits.php">Benefits Information</a> <a href="#contact">Scheduling</a> <a href="#about">Links</a> </div>

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! This works, but now my url is staying the same when switching menu items.
That's because you've used preventDefault() which stops the page redirection. If you want to highlight the current page link when changing page you need to do this in a completely different way. You would need to recognise the new page as it loads and then put the class on the matching link within the JS of that page, not the one on which the link was clicked.
Ah okay I see. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.