CJ408 CJ408 - 3 months ago 9
Javascript Question

How to toggle off an element when another element is activated?

I have two elements.
if 1 is already toggled on, then when I toggle on 2, 1 should toggle off.
I am still new to javascript, so if someone wuold help please thanks. Right now, when I try to click, nothing happens, if I remove the while loop, then it works. Maybe I have some error in there that I am unsure off, but it looks right base on the logic.

<style>
.mystyle {
width: 300px;
height: 50px;
background-color: coral;
color: white;
font-size: 25px;
}

.newClassName {
width: 400px;
height: 100px;
background-color: lightblue;
text-align: center;
font-size: 25px;
color: navy;
margin-bottom: 10px;
}
</style>
</head>
<body>

<p>Click the button to toggle between two classes.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction2()">Try it 2</button>

<div id="myDIV" class="mystyle">
I am a DIV element
</div>

<div id="myDIV2" class="mystyle">
I am a DIV element2
</div>
<script>
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
function myFunction() {
x.classList.toggle("newClassName");
}
function myFunction2() {
y.classList.toggle("newClassName");
}
while (x.classList.contains("newClassName")) {
if (y.classList.contains("newClassName") = true) {
x.classList.toggle("newClassName");
}
}

</script>
</body>

Answer

You may reduce all to only one function because, from MDN:

toggle ( String [, force] ) When only one argument is present: Toggle class value; i.e., if class exists then remove it and return false, if not, then add it and return true. When a second argument is present: If the second argument is true, add specified class value, and if it is false, remove it.

So the code is:

var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
function myFunction() {
  var result = x.classList.toggle("newClassName");
  y.classList.toggle("newClassName", !result);
}
.mystyle {
  width: 300px;
  height: 50px;
  background-color: coral;
  color: white;
  font-size: 25px;
}

.newClassName {
  width: 400px;
  height: 100px;
  background-color: lightblue;
  text-align: center;
  font-size: 25px;
  color: navy;
  margin-bottom: 10px;
}
<p>Click the button to toggle between two classes.</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction()">Try it 2</button>

<div id="myDIV" class="mystyle">
    I am a DIV element
</div>

<div id="myDIV2" class="mystyle">
    I am a DIV element2
</div>