Eugenio Segala
Eugenio Segala

Reputation: 55

show category after click (jquery)

I made this simple script:

var jq111 = jQuery.noConflict();

jq111( ".main-cat" ).click(function() {
  jq111( ".child" ).toggle( "slow" );
});

This show child category when i click on main-cat.

Example:

CAR

  • Audi <- show after click
  • Ferrari <- show after click
  • Fiat <- show after click

I have a problem that,all main category drop her child when i click one of their.

Another main category:

Bicycle, Motorcycle etc..

The categories are dynamic, all main have the same class because they are output by loop.

How can I expand only the categories within its container?

HTML:

 <ul class="main-cat">
 <li><a href="#">CAR</a>

 <ul class="child">
 <li><a href="#">Ferrari</a></li>
 <li><a href="#">Fiat</a></li>
 <li><a href="#">Lamborghini</a></li>
 </ul>
 </li>

 <ul class="main-cat">
 <li><a href="#">Motorcycle</a>

 <ul class="child">
 <li><a href="#">Honda</a></li>
 <li><a href="#">Example</a></li>
 <li><a href="#">Example</a></li>
 </ul>
 </li>

Upvotes: 2

Views: 91

Answers (2)

Franco
Franco

Reputation: 2329

Try this:

<ul class="main-cat">
    <li><a href="#">CAR</a>

     <ul class="child">
     <li><a href="#">Ferrari</a></li>
     <li><a href="#">Fiat</a></li>
     <li><a href="#">Lamborghini</a></li>
     </ul>
 </li>
 </ul>

<ul class="main-cat">
    <li><a href="#">BICYCLE</a>

     <ul class="child">
     <li><a href="#">Bike 1</a></li>
     <li><a href="#">Bike 2</a></li>
     <li><a href="#">Bike 3</a></li>
     </ul>
 </li>
 </ul>

NOTE: the structure of the elements. They are wrapped in its own 'ul' tags

And your javascript:

$(document).ready(function() {

       var jq111 = jQuery.noConflict();

       jq111('.main-cat ul').hide() //hide all by default

       jq111( ".main-cat" ).click(function() {
            jq111('.main-cat ul').hide() //this will hide the elements if one is already open
            jq111(this).find( ".child" ).show( "slow" );
       });

 });

The working demo is here:

https://jsfiddle.net/5j8ne1tz/

Upvotes: 2

Aric Watson
Aric Watson

Reputation: 124

It's hard to make a definite recommendation without see the actual HTML - but perhaps this will work?

    var jq111 = jQuery.noConflict();

    jq111( ".main-cat" ).click(function() {
            jq111(this).find( ".child" ).toggle( "slow" );
    });

That should find each .child element below the .main-cat classed element that was clicked.

Upvotes: 0

Related Questions