0

function openclass(className) {
  var i;
  var x = document.getElementsByClassName("standard");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  document.getElementById(className).style.display = "block";
}
<div class="page-header">
  <button type="button" class="btn btn-primary active" aria-pressed="true" onclick="openclass('viewclass')">View Class</button>
  <button type="button" class="btn btn-primary" aria-pressed="true" onclick="openclass('addclass')">Add Class</button>
  <button type="button" class="btn btn-primary" onclick="openclass('addsection')">Add Section</button>
  <button type="button" class="btn btn-primary" onclick="openclass('assignteacher')">Assign Teacher</button>
</div>

<div id="viewclass" class="standard">
  <h1>View Class</h1>

</div>

<div id="addclass" class="standard" style="display:none">
  <h2>Add Class</h2>
</div>

<div id="addsection" class="standard" style="display:none">
  <h2>add section</h2>
</div>

<div id="assignteacher" class="standard" style="display:none">
  <h2>assign teacher</h2>
</div>

With first button already active, I want to make every other button active on click and and remove older active, I know it can be done through js but really can't seem to figure it out

MetropolisCZ
  • 567
  • 1
  • 8
  • 20

1 Answers1

2

You just need to add the clickedbutton inside the onclick arguments. You can do that by using the this keyword. So onclick=openClass(this, 'className')

And then, on click, remove all the ' active classes ' and add the active class to the clickedButton

function openclass(clickedBtn, className) {
  var i;
  var x = document.getElementsByClassName("standard");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  document.getElementById(`${className}`).style.display = "block";
  // add remove active class
  document.querySelectorAll('.btn').forEach(btn => btn.classList.contains('active') && btn.classList.remove('active'))
    clickedBtn.classList.add('active')

}
.btn.active {
    background:Red;
}
<div class="page-header">
   <button type="button" class="btn btn-primary active" aria-pressed="true" onclick="openclass(this,'viewclass')">View Class</button>
   <button type="button" class="btn btn-primary" aria-pressed="true" onclick="openclass(this, 'addclass')">Add Class</button>
   <button type="button" class="btn btn-primary" onclick="openclass(this,'addsection')">Add Section</button>
   <button type="button" class="btn btn-primary" onclick="openclass(this,'assignteacher')">Assign Teacher</button>
 </div>

 <div id="viewclass" class="standard">
   <h1>View Class</h1>

 </div>

 <div id="addclass" class="standard" style="display:none">
   <h2>Add Class</h2>
 </div>

 <div id="addsection" class="standard" style="display:none">
   <h2>add section</h2>
 </div>

 <div id="assignteacher" class="standard" style="display:none">
   <h2>assign teacher</h2>
 </div>
Mihai T
  • 17,254
  • 2
  • 23
  • 32