Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS to highlight active link in a table of contents based on URL pattern

Tags:

jquery

css

I have a div that contains a UL element with each of my page's table of contents.

Currently, I'm having to hardcode a special class on the active element (class="active"). However, I'm trying to see if I can use CSS3 to do the work by matching the href to the browser's current URL.

For example, if the href in the toc div's anchor matches the current URL of the page, add a special formatting to it.

Example URL: http://mysite.com/page-title/2

Markup:

<div class="toc">
    <h3>Table of Contents</h3>
    <ul>
        <li><a href="http://mysite.com/page-title/">Part 1</a></li>
        <li><a href="http://mysite.com/page-title/2">Part 2</a></li>
        <li><a href="http://mysite.com/page-title/3">Part 3</a></li>
    </ul>
</div>

In the above example, I want to apply a special css formatting to the second list item element, since its HREF pattern has a match "/2" with the URL pattern.

If this is not doable via CSS, I can place it in my jQuery script if you can provide the jQuery code.

like image 440
RegEdit Avatar asked Sep 04 '25 16:09

RegEdit


2 Answers

with jQuery something like following should work;

var urlString = window.location; // or try window.location.pathname

$('a[href="' + urlString + '"]').addClass("active");
like image 177
Turcia Avatar answered Sep 07 '25 17:09

Turcia


There is no need for JavaScript here. Just add a class to the body tag that corresponds to the current page, and add that same class to the nav items. Then create a css rule for the matched sets like so:

<body class="products">
<div class="toc">
    <h3>Table of Contents</h3>
    <ul>
        <li><a href="http://mysite.com/page-title/" class="products-nav">Product Overview</a></li>
        <li><a href="http://mysite.com/page-title/2" class="home-nav">A More Dynamic Home Page</a></li>
        <li><a href="http://mysite.com/page-title/3" class="images-nav">Featured Images on Steroids</a></li>
    </ul>
</div>

and

<body class="home">
<div class="toc">
    <h3>Table of Contents</h3>
    <ul>
        <li><a href="http://mysite.com/page-title/" class="products-nav">Product Overview</a></li>
        <li><a href="http://mysite.com/page-title/2" class="home-nav">A More Dynamic Home Page</a></li>
        <li><a href="http://mysite.com/page-title/3" class="images-nav">Featured Images on Steroids</a></li>
    </ul>
</div>

etc. then:

.products .products-nav, .home .home-nav, .images .images-nav {
    font-weight: bold;
}
like image 43
markle976 Avatar answered Sep 07 '25 18:09

markle976