Ronnie Beltran
Ronnie Beltran

Reputation: 604

jquery highlight menu

I have this script that highlight the nav menu when clicked but after the click the selected class disappears. Is there a workaround in here to make the selected class in effect after the clicked?

<script type="text/javascript">
$( document ).ready( function() {
    $( '#nav ul li a' ).click( function() {
        $( '#nav ul li' ).removeClass( 'selected' );
        $( this ).parent( 'li' ).addClass( 'selected' );
        alert('hello');
    });
});

</script>
    <div id="nav"> 
        <ul>    
            <li><a href="/">Home</a></li>
            <li><a href="/blog/">Blog</a></li>
            <li><a href="/about/">About</a></li>
        </ul>
    </div>

Upvotes: 1

Views: 4228

Answers (2)

mekwall
mekwall

Reputation: 28974

You can use the .siblings method to get the li elements which have the selected class.

$( document ).ready( function() {
    $( "#nav ul li a" ).click( function() {
        $( this ).parent( "li" )
            .addClass( "selected" )
            .siblings( ".selected" )
                .removeClass( "selected" );
        return false;
    });
});

You can see this in action on jsFiddle.

Upvotes: 2

gearsdigital
gearsdigital

Reputation: 14205

If i understand you correctly... Example: http://jsfiddle.net/jgmgW/

$( document ).ready( function() {
   $( '#nav ul li' ).click( function() {
       $( '#nav ul' ).children('li').removeClass();
      $( this ).addClass( 'selected' );
   });
});

#nav .selected a{background:red;display:block}

<div id="nav">
    <ul>    
        <li><a href="#">Home</a></li>
        <li><a href="#">Blog</a></li>
        <li><a href="#">About</a></li>
    </ul>
</div>

Upvotes: 0

Related Questions