Monday, 22 April 2013

jQuery: Change color of selected navigation menu item

Scenario:
I want to change the color of the selected menu item.

Solution:
In order to achieve this, I have created a menu using html.secondly, I need a css class say for example "menuLinkSelected" which will define the text and background color of the selected menu. I have the css class, now I need to find a way to add this class to the selected menu. I can add a class when a menu link is clicked using javascript. Other thing I need to do is to remove this class "menuLinkSelected" when other item is changed or clicked.

HTML Menu:
<div id="menu">
    <ul>
        <li>
            <a href="#" class="menuLinkUnselected">Home</a>
            <a href="#" class="menuLinkUnselected">Services</a>
            <a href="#" class="menuLinkUnselected">Gallery</a>
            <a href="#" class="menuLinkUnselected">Portfolio</a>
            <a href="#" class="menuLinkUnselected">About</a>
        </li>
    </ul>

</div>
CSS classes:
#menu a.menuLinkUnselected
{
    display: block;
    float: left;
    color: #FFFFFF;
    width: 120px;
    text-align: center;
    padding: 4px;
    margin:0px;
    text-decoration:none;
}

#menu a.menuLinkUnselected:hover
{
    display: block;
    background-image: url('../../Images/System/but_hov.png');
    background-repeat: no-repeat;
    background-position: center;
}

.menuLinkSelected
{
    display: block;   
    background-image: url('../../Images/System/but_hov.png');
    background-repeat: no-repeat;
    background-position: center;

}

JQUERY to add selected and unselected class:
this script will be loaded when document is loaded.
<head>
<script type="text/javascript">
    $(document).ready(function () {
        $('a.menuLinkUnselected').click(function () {
            $(this).addClass('menuLinkSelected');
            $(this).siblings().removeClass('menuLinkSelected');
  //$('nav li').click( function() {
  //  $(this).addClass('active').siblings().removeClass('active');
  //});
}); }); </script>
</head>
Just think of what the words "child" and "descendant" mean in English:
  • My daughter is both my child and my descendant
  • My granddaughter is not my child, but she is my descendant.

No comments:

Post a Comment