RMont
RMont

Reputation: 33

Using JS to hide accordion content similar to tab table

I have this code functioning the way I want, except that I don't want someone to be able to open more than one "tab" at a time. I'm not sure how to make Javascript remove the "transform-active" class from a div that currently has it if it's added to another div by way of clicking its button.

function Slidein(num) {
   var element = document.getElementById(num);
   element.classList.toggle("transform-active");
}
.tabcontent {
  background-color: #218D9B;
 overflow: hidden;
  height: 0px;
  width: 600px;
}

.transform{
  -webkit-transition: .7s;  
  -moz-transition: .7s;  
  -o-transition: .7s;  
  -ms-transition: .7s;  
  transition: .7s;
}

.transform-active {
  background-color: #45CEE0;
  height: 200px;
  width: 600px;
  visibility: visible;
}
  
<button id="button1" onclick="Slidein('div1')">Button 1</button>
<button id="button2" onclick="Slidein('div2')">Button 2</button>
<button id="button3" onclick="Slidein('div3')">Button 3</button>

<div id="div1" class="tabcontent transform">
  Here's some text in my FIRST div
</div>

<div id="div2" class="tabcontent transform">
  This would be the SECOND div text
</div>

<div id="div3" class="tabcontent transform">
  And now we have a THIRD div with its text
</div>

Upvotes: 1

Views: 86

Answers (1)

Krystian
Krystian

Reputation: 79

Maybe change Slidein to something like this:

function Slidein(num) {    
      var elementWithTransformActiveClass = document.querySelector('.transform-active');
      var element = document.getElementById(num);
      if (!!elementWithTransformActiveClass) elementWithTransformActiveClass.classList.remove("transform-active");
      if (element !== elementWithTransformActiveClass) element.classList.add("transform-active");
}

EDIT:

You can access active button:

var buttonId = num.replace('div', 'button'); 
var button = document.getElementById(buttonId); 

// and now you can add a new class to the button 

button.classList.add('new-class');


function Slidein(num) {    
      var elementWithTransformActiveClass = document.querySelector('.transform-active');
      var element = document.getElementById(num);
      if (!!elementWithTransformActiveClass) elementWithTransformActiveClass.classList.remove("transform-active");
      if (element !== elementWithTransformActiveClass) {
           element.classList.add("transform-active");

           var buttonId = num.replace('div', 'button'); 
           var button = document.getElementById(buttonId); 

           // and now you can add a new class to the button 

           button.classList.add('new-class');
      }
}

To see all properties and methods can be used on all HTML elements visit: w3schools.com/jsref/dom_obj_all.asp

Upvotes: 1

Related Questions