0

I'm adding a class with addClass() to an element the user clicked on with

$('.question').click(function() {
    $(this).next('.answer').slideDown();
    $(this).addClass('open');
    $(this).next('.answer').siblings('.answer').slideUp();
    $(this).siblings('.question').removeClass('open');
});

This works fine. But now I will get the element with class="open" in order to slideUp() the answer below. But I can't get it to work. I tried

$('.open').click(function() {
    $(this).next('.answer').slideUp();
    $(this).removeClass('open');
});

and

$('.open').on('click' function() {
    $(this).next('.answer').slideUp();
    $(this).removeClass('open');
});

Do you have any advice?

j08691
  • 204,283
  • 31
  • 260
  • 272
Ralph
  • 35
  • 1
  • 8

1 Answers1

0

Since you are changing the class dynamically, you need to use event delegation for binding click

$(dodcument).on('click','.open', function() {
    $(this).next('.answer').slideUp();
    $(this).removeClass('open');
});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53