5

I have a set of tabs in html which I want to highlight when selected. I am trying to use jquery to do this. But it does not seem to work.

$(function () {
    setNavigation();
});

function setNavigation() {
    var path = window.location.pathname;
    path = path.replace(/\/$/, "");
    path = decodeURIComponent(path);

    $(".nav a").each(function () {
        var href = $(this).attr('href');
        if (path.substring(0, href.length) === href) {
            $(this).closest('li').addClass('active');
        }
    });
}
a {
    color:#000;
    text-decoration:none;
}
a:hover {
    text-decoration:underline;
}
a:visited {
    color:#000;
}
.nav {
    padding:10px;
    border:solid 1px #c0c0c0;
    border-radius:5px;
    float:left;
}
.nav li {
    list-style-type:none;
    float:left;
    margin:0 10px;
}
.nav li a {
    text-align:center;
    width:55px;
    float:left;
}
.nav li.active {
    background-color:green;
}
.nav li.active a {
    color:#fff;
    font-weight:bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="nav">
        <li><a href="#tab1">tab1</a>
        </li>
        <li>|</li>
        <li><a href="#tab2">tab2</a>
        </li>
        <li>|</li>
        <li><a href="#tab3">tab3</a>
        </li>
        <li>|</li>
        <li><a href="#tab4">tab4</a>
        </li>
    </ul>
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
chidori
  • 1,052
  • 3
  • 12
  • 25
  • what are your expectations with regard to url matching? Will hash that matches href be in url? – charlietfl Oct 22 '14 at 16:54
  • Actually , the answers submitted by folks here meets my requirement. But what if I am trying to load this url from each
  • element and the param passed each time is different one and I want to highlight the tab(url) that got loaded. The code given here does not seem to work for that. I want to addClass to li which points to a URL
  • – chidori Oct 23 '14 at 14:42
  • that's what I expected, so use `location.hash` and match the href that way – charlietfl Oct 23 '14 at 14:45
  • location.hash does not seem to work when I am calling link as `url?data=a` and sometimes `url?data=a;col=1;col2=alpha` , where i am interested in knowing only what param **data** holds . – chidori Oct 23 '14 at 14:53
  • 1
    ok, well that's why I asked about the url. Parse `location.search` then. Can also find numerous posts on how to convert `location.search` to an object also – charlietfl Oct 23 '14 at 14:55
  • @charlietfl , Thanks. Your suggestions helped. Also , thanks to the forum I found a useful [link](http://stackoverflow.com/questions/19491336/get-url-parameter-jquery) related to this issue. – chidori Oct 23 '14 at 15:13