1

I have the following code to show and hide a div but if I want to click on the image I can add the class but if I want to remove it by clicking the image then it will open it again. Can anyone explain to me how this works?

https://jsfiddle.net/bmhv3edw/

$(document).ready(function() {
    function close_answer_section() {
        $('.question-text').removeClass('active');
        $('.answer-section-content').slideUp(300).removeClass('open');
    }

    $('.question-text').click(function(e) {
        var currentAttrValue = $(this).attr('href');

        if($(e.target).is('.active')) {
            close_answer_section();
        }else {
            close_answer_section();

            $(this).addClass('active');
            $('.questions ' + currentAttrValue).slideDown(300).addClass('open'); 
        }

        e.preventDefault();
    });
});

2 Answers 2

3

You can see that when you clicked on the img, the e.target is <img>, as it don't have class .active, it'll always trigger the false part.

Solution, change

if($(e.target).is('.active')) {

to

if($(this).is('.active')) {

See jsFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

That was so easy. Cheers
2

You can greatly simplify your logic by using slideToggle() on the current .answer-section-content, and slideUp() on all the rest:

$('.question-text').click(function() {
  var answer= $(this).next('.answer-section-content');
  answer.slideToggle(300); 
  $('.answer-section-content').not(answer).slideUp(300);
});

This allows you to remove the ids from the answers and the hrefs from the divs.

$(document).ready(function() {
  $('.question-text').click(function() {
    var answer= $(this).next('.answer-section-content');
    answer.slideToggle(300); 
    $('.answer-section-content').not(answer).slideUp(300);
  });
});
body{ background: black };
.questions{
  padding-top: 25px;
  padding-left: 170px;
  padding-bottom: 25px;
}
.question{
  padding: 5px;
  font-size: 18px;
  font-weight: 100;
  color: #ffffff;
}
.answer-section-content {
  display:none;
  padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="questions">
  <div class="question">
    <div class="question-text">
      <img src="images/plus-eclipse.png">Question 1</div>
    <div class="answer-section-content">
      <p>Answer 1</p>
    </div>
  </div>
  <div class="question">
    <div class="question-text">
      <img src="images/plus-eclipse.png" />Question 2</div>
    <div class="answer-section-content">
      <p>Answer 2</p>
    </div>
  </div>
</div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.