user1999510
user1999510

Reputation:

jquery add or remove class using toggleClass() within on click method

Hi i created accordion function using jquery by toggleClass function.

my fiddle for this case

here while clicking accordion class a active class will added to the same class i added some styles to active class for displaying child classes.Now the problem is the accordion toggled if we click anywhere of accordion class or its child classes whats wrong on it? my JS

$('.accordion').on('click', function() {
            $(this).toggleClass('active'); 
        });

Upvotes: 0

Views: 9777

Answers (3)

Manish Kumar
Manish Kumar

Reputation: 10482

Try this:

   $('.accordion > a.title').on('click', function() {
       $(this).parent().toggleClass('active'); 
   });

or

   $('a.title').on('click', function() {
       $(this).parent().toggleClass('active'); 
   });

here is updated Demo

Upvotes: 0

NaYaN
NaYaN

Reputation: 1320

you have to use .parent() of Jquery function.

$('.title').on('click', function() {
    $(this).parent().toggleClass('active'); 
});

Live Demo

Upvotes: 1

Amadan
Amadan

Reputation: 198304

$('.accordion > a.title').on('click', function() {
  $(this).parent().toggleClass('active'); 
});

As RGraham says, there was nothing wrong with it, it was doing exactly what you told it to. If you want it to toggle only when you click on the title, then you need to catch the events on the title, not the whole accordion div.

Upvotes: 3

Related Questions