Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight the selected tab?

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>
like image 598
chidori Avatar asked Oct 22 '14 16:10

chidori


1 Answers

That is doable with a on click event:

$(document).on("click", 'ul li', function(){
    $('ul li').removeClass('active');
    $(this).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>
like image 129
just some guy Avatar answered Oct 13 '22 05:10

just some guy