user2794024
user2794024

Reputation: 39

click element without affecting other elements with the same structure

I have an HTML element with same structure but I wanted my jquery to affect only the particular element I clicked instead it affects all elements in the DOM. Here's my fiddle.

//HTML Code
<div class="category">
<h3>This is the title</h3>
<ul>
    <li>Sub menu one</li>
    <li>Sub menu two</li>
    <li>Sub menu three</li>
    <li>Sub menu four</li>
    <li>Sub menu five</li>
    <li>Sub menu six</li>
    <li>Sub menu seven</li>
</ul>
</div>
<div class="category">
    <h3>This is the title</h3>
<ul>
    <li>Sub menu one</li>
    <li>Sub menu two</li>
    <li>Sub menu three</li>
    <li>Sub menu four</li>
    <li>Sub menu five</li>
    <li>Sub menu six</li>
    <li>Sub menu seven</li>
</ul>
</div>

//jquery

$(function(){
   $('.category > h3').click(function(){
     $('.category > ul').slideToggle("fast");
      });


$('.category > h3').click(function(event){
    $(this).toggleClass('clicked')
    });

 }); 

Upvotes: 0

Views: 134

Answers (5)

Rakesh Juyal
Rakesh Juyal

Reputation: 36759

Use

$(this).next('ul').slideToggle("fast");

Instead of

$('.category > ul').slideToggle("fast");

Upvotes: 0

Stefan Steiger
Stefan Steiger

Reputation: 82196

Or like this, may be a little bit less susceptible to changes

$(function(){
   $('.category > h3').click(function(){
     $(this).find('.category > ul').slideToggle("fast");
  });

Upvotes: 0

Manu M
Manu M

Reputation: 1064

You can use next function for this, also it is better to combine the two click events for better performance like this

$(function(){
 $('.category > h3').click(function(){
   $(this).next("ul").slideToggle("fast");
   $(this).toggleClass('clicked')
 });


});    

http://jsfiddle.net/tnsWj/8/

Upvotes: 0

Jason OOO
Jason OOO

Reputation: 3552

use

   $('.category > h3').click(function(){
     $(this).next("ul").slideToggle("fast");
  });

DEMO

Upvotes: 0

Abhishek Jain
Abhishek Jain

Reputation: 2607

Try this:

  $(function(){
   $('.category > h3').click(function(){
     $(this).next().slideToggle("fast");
  });

Fiddle

Upvotes: 2

Related Questions