Anna Lam
Anna Lam

Reputation: 807

CSS - highlight a selected tab

I have the following tabbed navigation setup in my master page.

        <nav class="grid_12">
            <ul>
                <li><a href="#" class="selected">Home</a></li>
                <li><a href="#">Portfolio</a></li>
                <li><a href="#">Blog</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>

When I click on the Portfolio tab, for example, I'd like the Portfolio tab to remain highlighted when I land on the portfolio page. What is the recommended way to accomplish this?

I have checked some other posts, but the most relevant of those uses divs in the example as opposed to separate pages.

Upvotes: 2

Views: 2064

Answers (1)

Sammy
Sammy

Reputation: 3099

Assuming the "selected" class name you have has the styling for the highlight you're talking about. After the user clicks on one of those links, with jquery you can add "selected" class to the clicked anchor tag. put this at the bottom of your page right before the closing body tag or in your main JavaScript file.

<script type="text/javascript">
    $(document).ready(function () {
        $(".grid_12 ul li a").click(function() {
            $(".grid_12 ul li a ").removeClass("selected");
            $(this).addClass("selected")
        })
    })
</script>

The code above will only work if there is no page refresh and only content refresh, however if your page will refresh and go to a new page I would do something like this:

<nav class="grid_12">
    <ul>
        <li><a href="#" class="nav_home">Home</a></li>
        <li><a href="#" class="nav_portfolio">Portfolio</a></li>
        <li><a href="#" class="nav_blog">Blog</a></li>
        <li><a href="#" class="nav_contact">Contact</a></li>
    </ul>
 </nav>

and add the styling for specific pages. For example when you're on www.mySite.com/portfolio in the css for portfolio ONLY add:

a.nav_portfolio{
    background-color:orage;
    ...
}

This way you don't even have to do any javascript.

Upvotes: 3

Related Questions