atoms
atoms

Reputation: 3093

Jquery drop down menu, reuse function

Im trying to create some jquery that onClick drops down the child menu item.

I have made some Jquery that works, but its specific to the element, and would need to be written over and over for a big menu.

Is there a way I can detect the element clicked, then find its child element and slide toggle to show/hide.

See the fiddle: http://jsfiddle.net/c5tnje9x/

$("#sub1").click( function () {
        $("#sub11").slideToggle(200);
    });

$("#subTwo").click( function () {
    $("#subThree").slideToggle(200);
});

and the HTML

<ul>
    <li>Home</li>

    <li>
        <a href="#" id="sub1">first +</a>
        <ul id="sub11" style="background: grey;display: none;">
            <li>Sub1</li>
            <li><a href="#" id="subTwo">sub1.1+</a>
                <ul id="subThree" style="background: green;display: none;">
                    <li>Sub Three</li>
                </ul>
            </li>
        </ul>
    </li>
        <li>seccond</li>
        <li class="hasSub"><a href="#">Third +</a>
            <ul style="background: green;display: none;">
                <li>sub 2</li>
                <li>sub 2.2</li>
            </ul>
        </li>
        <ul>
            <li>Sub 2</li>
        </ul>
</ul>

Upvotes: 0

Views: 444

Answers (3)

Jason
Jason

Reputation: 7682

A couple of points -

Use classes instead of ID's. Classes are reusable, IDs are not.

Give your ul a class 'foo', then you can do something like:

$('ul.foo > li a').on('click', function() {
    $(this).next('ul').slideToggle(200);
);

This basically says - on top menu click, find the corresponding ul and open it.

But that will only open the drop menu, and will not close the others. You didn't explicitly state that's what you were doing, so I did not address that here.

A simple approach is laid out here: http://toddmotto.com/html5-and-jquery-super-simple-drop-down-nav/

Upvotes: 1

Shijin TR
Shijin TR

Reputation: 7768

Try this

DEMO

Javacsript

$('#nav > li > ul').hide();

$('#nav > li > a').click(function(){
$(this).next('ul').slideToggle(200);
});

HTML

<ul id="nav">

<li>
    <a href="#">main1+</a>
   <ul>
       <li>sub1</li>
       <li>sub2</li>
   </ul>    

</li>

<li>
    <a href="#">main2+</a>
   <ul>
       <li>sub1</li>
       <li>sub2</li>
   </ul>    

</li>

   <li>
    <a href="#">main2+</a>
   <ul>
       <li>sub1</li>
       <li>sub2</li>
   </ul>    

</li>

  </ul>    

Upvotes: 5

Manwal
Manwal

Reputation: 23816

You can simply give them a same class dropdown

Use single jquery click function on class:

$(".dropdown").click( function () {
        $(this).next('ul').slideToggle(200);
    });

DEMO

Upvotes: 3

Related Questions