dimanche 22 août 2021

Why do I have to click button twice for this JavaScript function to work?

I'm trying to get this function to change the display to the "active" div on first click then back to "Insurance" on the second click. Currently it doesn't change to "active" until the second click of the button, then it rotates back and forth as it should. Why does it take 2 clicks initially? How do I get it to work on the first click of the button?

var timesClicked = 0;

function openDiv(evt, divName, divName2) {
  if (name1 === 'Insurance' && timesClicked < 1) {
    evt.currentTarget.className += " active";
  }

  var name1 = divName;
  var name2 = divName2;
  timesClicked++;
  if (name1 !== 'Insurance' && timesClicked > 1) {
    //        timesClicked = 0;
    //        openDiv(evt, 'Insurance', 'Insurance2');
    //        console.log("switch back");
    //        return;
    name1 = 'Insurance';
    name2 = 'Insurance2';
    evt.currentTarget.className.replace(" active", "");
    timesClicked = 0;
  }
  var i, tabcontent, tabcontent2, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  tabcontent2 = document.getElementsByClassName("tabcontent2");
  for (i = 0; i < tabcontent2.length; i++) {
    tabcontent[i].style.display = "none";
    tabcontent2[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  document.getElementById(name1).style.display = "block";
  document.getElementById(name2).style.display = "block";
  if (timesClicked === 1) {
    evt.currentTarget.className += " active";
  }

}

document.getElementById("defaultOpen").click();
<button class="tablinks" onclick="openDiv(event, 'Insurance', 'Insurance2')" id="defaultOpen"></button>
<div class="dw12">
  <button class="tablinks" onclick="openDiv(event, 'Retiree-Medical', 'Retiree-Medical2')"><div class="tab---icon"><img class="tab-img" src="images/retiree-medical_icon.png" alt="Retiree Medical"/></div><div class="shadow-div"></div><p class="bold-title"><strong>RETIREE MEDICAL</strong></p><p class="small-title">CLICK FOR MORE</p></button>
</div>

Aucun commentaire:

Enregistrer un commentaire