Search code examples
javascriptselectors-api

If Previous Content Div is Open, Close It and Open the Next (Plain JavaScript)


I have this simple dropdown faq system, I only want one content div to be open at a time, so I tried to use an if / else condition, but I can only make it work halfway.

  1. I'm checking if the content div next to the trigger div has class is-visible — if not, add that class (this works)

  2. But if the previous content div has (contains) class is-visible, I want to remove it, so only one content div is open at a time.

I've tried so many different conditions but I think I'm overcomplexifying it, this should be simple enough right?

https://jsfiddle.net/notuhm05/1/

var faqTrigger = document.querySelectorAll('.mm-faq-trigger');
for (var i = 0; i < faqTrigger.length; i++) {
    faqTrigger[i].addEventListener('click', function() {
      if (!this.nextElementSibling.classList.contains('is-visible')) {
        this.nextElementSibling.classList.add('is-visible');
      } else if (this.previousElementSibling.classList.contains('is-visible')) {
        this.nextElementSibling.classList.remove('is-visible');
      } else {
        console.log("doesn't work");
      }
    });
}

Would greatly appreciate some pointers here! :-)


Solution

  • Here is a working solution:

    • Toggle the class is-visible on the clicked node
    • Iterate through all triggers and remove the class is-visible if the id of the href tag does not match the clicked nodes id. NOTE: I had to add an id property to the trigger href tag like <a id="1" href="#" class="mm-faq-trigger">Trigger</a>
    • Source Code:

      var faqTrigger = document.querySelectorAll('.mm-faq-trigger');
      for (var i = 0; i < faqTrigger.length; i++) {
          faqTrigger[i].addEventListener('click', function() {
          this.nextElementSibling.classList.toggle('is-visible');
      
          for (var i = 0; i < faqTrigger.length; i++) {
              var trigger = faqTrigger[i];
              if (trigger.nextElementSibling !== null && trigger.id !== this.id)  {
                  trigger.nextElementSibling.classList.remove('is-visible');
             }    
          }    
      });
      }