use jquery to mark a link as active depending on the url

Hello,

I have:

<div class="col-left sidebar"><ul>
<li><a href="/installation" class="button-link">Installation</a></li>
<li><a href="/tuning" class="button-link">Tuning</a></li>
<li><a href="/101" class="button-link">101</a></li>
<li><a href="/about-us" class="button-link">About</a></li>
<li><a href="/tour-our-facility" class="button-link">Tour Our Facility</a></li>
<li><a href="/meet-the-team" class="button-link">Meet The Team</a></li>
<li><a href="/careers" class="button-link">Careers</a></li>
<li><a href="/contact" class="button-link">Contact Dyno-Comp</a></li>
</ul></div>

Open in new window


Is there a way to add the class 'active' if the url is the href with jquery?
LVL 1
movieprodwAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
This JQuery should do it
$(function() {
  var path = window.location.pathname;
  
  $('.sidebar li a').each(function() {
    if ($(this).attr('href') == path) {
      $(this).addClass('active');
    }
  });
});

Open in new window

Sample here
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
movieprodwAuthor Commented:
Beautiful! Thank you
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.