Amelie Amelie - 4 months ago 10
HTML Question

Button unclicked says 'see', button clicked says 'close'

I have a faq list that displays that way : question and button "see the answer".

When "see the answer" is clicked, it immediatly becomes "close".

My problem is I can't reverse it when "close" is clicked. It should become a "see the answer" button again.

Here is the html

<p class="faq-question">Question</p>
<div class="collapse js-faq-answer" id="collapseExample">
<div class="well">
Answer
</div>
</div>
<a class="btn btn-primary js-faq-button" role="button" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">See the answer</a>


And here is my script

$(document).ready(function() {
$('.js-faq-button').click(function(){
if(this.click){
$(this).addClass('js-faq-button-clicked');
$(this).removeClass('js-faq-button');
$('.js-faq-button-clicked').html('Close');
}
else{
$(this).addClass('js-faq-button');
$(this).removeClass('js-faq-button-clicked');
$('.js-faq-button-clicked').html('See the answer');
}
});
});

Answer

Your condition is incorrect. I'd check to see if button has the js-faq-button-clicked class. If not add it, if so, remove it.

This isn't the only way, but it will certainly work.

$(document).ready(function() {
    $('.js-faq-button').click(function(){
        if(!$(this).hasClass("js-faq-button-clicked")){
            $(this).addClass('js-faq-button-clicked');
            $(this).removeClass('js-faq-button');
            $('.js-faq-button-clicked').html('Close');
        }
        else{
            $(this).addClass('js-faq-button');
            $(this).removeClass('js-faq-button-clicked');
            $('.js-faq-button-clicked').html('See the answer');
        }
    });
});
Comments