jQuery Automatically Highlight Current Page


Demo Download

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

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.
  1. 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..

  2. 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.

  3. 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.

    1. 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

Leave a Reply

Your email address will not be published. Required fields are marked *