Styling current page menu link using jQuery

We can easily style the current page url in menubar using jquery. All you have to do is just follow to snippets.

[code lang="css"]
#menu ul{ list-style-type:none; width:100%; background:#000000}
#menu li{padding:5px;display:inline-block}
#menu li a{ text-decoration:none; color:#FFFFFF; font-weight:bold}
#menu li a:hover{ background:#CCCCCC; color:#000000}
#menu li a:active{ background:#CCCCCC; color:#000000}
.current-menu{ background:#CCCCCC; padding:6px 5px 5px}
.current-menu a{ color:#000000;}
[/code]

Paste the css it in the header.

[code lang="php"]
<div id='menu'>
<ul>
<li><a href="http://localhost/menu/index.php">Home</a></li>
<li><a href="http://localhost/menu/products.php">Products</a></li>
<li><a href="http://localhost/menu/services.php">Services</a></li>
<li><a href="http://localhost/menu/contact.php">Contact</a></li>
</ul>
</div>
[/code]

Add the menu in your preferred location.

[code lang="js"]
var url =window.location;
$(".primary-menu a").each(function() {
if($(this).attr('href') == url){
$(this).addClass('current-menu');
}
});
[/code]

Add the above script after adding jQuery library.
jQuery.each() helps to go through all anchor tags.
To know more about each() 5 jQuery.each() Function Examples

Comments

Popular posts from this blog

Send email from xampp localhost

Convert long url to short url using tinyurl api

Modify item price in cart after placing order using sales_quote_add_item