1

I am trying to make a menu that slides down sub menu items (+changes background color) when clicked on. When a different menu item is clicked on, the other open should close (sub menu item slide back). I am using the html code below, (I am hiding the sub1 and sub2 by using dispay:none;)

Please view the code http://jsfiddle.net/kxvKA/

At the moment all slides open together, I want one to open at a time, and when the other is clicked on. the first should close

<ul class="nav">
            <li class="mainnav">MAINNAV</li>
                    <li class="sub1">SUB1</li>
                    <li class="sub2">SUB2</li>
</ul>
<ul class="nav">
            <li class="mainnav">MAINNAV2</li>
                    <li class="sub1">SUB1</li>
                    <li class="sub2">SUB2</li>
</ul>

and JQuery code

$(".mainnav").on("click", function(){
    $(".sub1, .sub2").slideDown("fast");
    $( ".mainnav" ).animate({
        backgroundColor: "#3A3A3A", 
        }, 500 );
});
singularity
  • 99
  • 2
  • 9

1 Answers1

0

In any jQuery event handler you get an event object with a lot of useful parameters. One of them is currentTarget which is a reference to the DOM element which triggered the event, so you can use it to do actions on the element which was interacted with even if the original selector applies to more than one element.

$(".mainnav").on("click", function(event) {
    $(".sub1, .sub2").slideUp("fast");
    $(event.currentTarget).siblings(".sub1, .sub2").slideDown("fast");
    $(event.currentTarget).animate({
        backgroundColor: "#3A3A3A", 
        }, 500 );
});

See updated Fiddle: http://jsfiddle.net/kxvKA/5/

Edit: oh, and if you want to animate color you'll have to use a plugin or jQuery UI, see: jQuery animate backgroundColor

Community
  • 1
  • 1
dain
  • 6,475
  • 1
  • 38
  • 47
  • Hi again...I have added a link to the siblings, when clicked on the required page loads, but the siblings disappear. I want the siblings to remain open ....Thanks – singularity May 26 '13 at 20:27
  • If you have a different question please post separately with full explanation and Fiddle :) – dain May 26 '13 at 21:44