0

Good day. I write tabs on javascript. The idea behind these tabs is soundly common, but there is a slight difference from the standard ones. When I click on the "+" button, all tabs should be closed and only the one that was clicked should open. Everything works well, but I just can not implement the closing of the tab on the second click of the button

enter image description here

HTML

        <div class="faq__tab">
          <div class="faq__tab__question">
            Какие вложения необходимы для того, чтобы<br>
            начать торговать на Wildberries?
            <div class="faq__tab__qeustion-btn" data-tab='0'></div>
          </div>
          <div class="faq__tab__answer">
            <span class="tab-answer">
              Какие вложения необходимы для того, чтобы<br>
              начать торговать на Wildberries?
            </span>
          </div>
        </div>

JS

const tabButtons = document.querySelectorAll('.faq__tab__qeustion-btn');
const tabAnswers = document.querySelectorAll('.faq__tab__answer');
const answer = document.querySelectorAll('tab-answer');

let tabClicked = false;

tabButtons.forEach((btn, index) => {

  btn.addEventListener('click', selectTab)

})

function selectTab() {

  tabButtons.forEach(button => {
    button.classList.remove('faq__tab__qeustion-btn--active');
  });

  tabAnswers.forEach(answer => {
    answer.classList.remove('faq__tab__answer--active');
  })

  this.classList.add('faq__tab__qeustion-btn--active');
  tabAnswers[this.getAttribute('data-tab')].classList.add('faq__tab__answer--active');

}

1 Answer 1

1

Save the original state of the tab in a variable, then toggle the opposite of the original state on the clicked tab after closing all.

tabButtons.forEach((btn) => {
    btn.addEventListener('click', selectTab)
});
function selectTab() {
    const tab = tabAnswers[this.dataset.tab];
    const makeThisActive = !tab.classList.contains('faq__tab__answer--active');
    tabButtons.forEach(button => {
        button.classList.remove('faq__tab__qeustion-btn--active');
    });
    tabAnswers.forEach(answer => {
        answer.classList.remove('faq__tab__answer--active');
    })
    this.classList.toggle('faq__tab__qeustion-btn--active', makeThisActive);
    tab.classList.toggle('faq__tab__answer--active', makeThisActive);
}

I'd also recommend fixing the qeustion - looks like a typo, and typos are frequent causes of bugs in programming.

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

1 Comment

Thank you very much, thanks to you I figured it out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.