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.
with jQuery something like following should work;
var urlString = window.location; // or try window.location.pathname
$('a[href="' + urlString + '"]').addClass("active");
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With