Websnippetz

Get cool snippets on php, css, jQuery, Magento and wordpress

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.

<br />      #menu ul{ list-style-type:none; width:100%; background:#000000}<br />      #menu li{padding:5px;display:inline-block}<br />      #menu li a{ text-decoration:none; color:#FFFFFF; font-weight:bold}<br />      #menu li a:hover{ background:#CCCCCC; color:#000000}<br />      #menu li a:active{ background:#CCCCCC; color:#000000}<br />      .current-menu{ background:#CCCCCC; padding:6px 5px 5px}<br />      .current-menu a{ color:#000000;}<br />

Paste the css it in the header.

<br />&lt;div id='menu'&gt;<br />&lt;ul&gt;<br />   &lt;li&gt;&lt;a href=&quot;http://localhost/menu/index.php&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br />   &lt;li&gt;&lt;a href=&quot;http://localhost/menu/products.php&quot;&gt;Products&lt;/a&gt;&lt;/li&gt;<br />   &lt;li&gt;&lt;a href=&quot;http://localhost/menu/services.php&quot;&gt;Services&lt;/a&gt;&lt;/li&gt;<br />    &lt;li&gt;&lt;a href=&quot;http://localhost/menu/contact.php&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt;<br />&lt;/ul&gt;<br />&lt;/div&gt;<br />

Add the menu in your preferred location.

<br />var url =window.location;<br />$(&quot;.primary-menu a&quot;).each(function() {<br />   if($(this).attr('href') == url){<br />      $(this).addClass('current-menu');<br />   }<br />});<br />

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

karthi s

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: