jQuery Automatically Highlight Current Page
In this tutorial, I will show how to automatically highlight current page link using jQuery. Newbie web developers face problem when they are doing custom development, hope this will help you.
Note: Don’t forget to include the jQuery library in the header or footer of web pages.
HTML
<div id="wrapper">
<ul class="navigation">
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
CSS
a {text-decoration:none;}
.active {background:yellow; padding:2px 6px;}
jQuery
$(function(){
var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);
$('.navigation a').each(function(){
if ($(this).attr('href') == pathname){
$(this).addClass('active');
}
});
});
If you found this tutorial helpful so kindly share it with your friends and leave your comment.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks
To get the pathname, simply do: `var pathname = window.location.pathname;`
Thanks to share helpful information with us. 🙂
Thanks you! from this is website i learned everything and improve my codinfg knowledge..
But i have want to know about AJAX in simple query..
Thanks for the code! Question. Is there any way to get this to work on the same page with a Nivo slider? The highlighting shows up perfectly but now the slider won’t work.
This may be due to class name conflict with my defined class, you can try using different class name for this highlight.
Hello,
I’m a newbie so can you tell me how you write code in the post? Do you use any special plugin?
Nice Post btw.
Thanks Indu to like my post, to show code your post in wordpress.com blog you will need to write your code between code language html, css or javascript tags in your post. I actually can’t write tag here if i write so it will be converted into html, so you can find those tags example here https://en.support.wordpress.com/code/posting-source-code/ and for self hosted blog you can use Crayon Syntax Highlighter
Follow my blog if you found it helpful, thanks
Thank You 🙂
You welcome, hope to see code in better layout in your blog soon 🙂