APAD1
APAD1

Reputation: 13666

jQuery adding a class to an li href using a hash?

I'm trying to code some jQuery to check if a link in my unordered list is the current page that is being viewed and then to add a class of "current" to that list item.

This is the code I am currently using:

$(document).ready(function() {
    //<![CDATA[
    jQuery(function() {
      jQuery('.sidebar li').each(function() {
        var href = jQuery(this).find('a').attr('href');
        if (href === window.location.pathname) {
          jQuery(this).addClass('current');
        }
      });
    });  
    //]]>
});

This works to an extent, but because all of the links in my sidebar are hashes, it always sets the current class on the first li. For example here is what my links look like:

<ul>
    <li><a href="/posts#page1" />Table of Contents</a></li>
    <li><a href="/posts#page10" />Chapter 1</a></li>
    <li><a href="/posts#page25" />Chapter 2</a></li>
</ul>

In this example, the current class is only applied to the "Table of Contents" li, even if you are on a different page.

Is it possible to accomplish what I'm trying in this way?

Thanks!

Upvotes: 0

Views: 244

Answers (1)

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

Just append location.hash to the pathname. It will be empty if there is none so it will work that way for links without one.

if (href === window.location.pathname + window.location.hash) {

Upvotes: 3

Related Questions