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
  • 197,815
  • 30
  • 248
  • 265
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
  • 24,863
  • 8
  • 29
  • 52