J. Doe J. Doe - 1 month ago 5
Javascript Question

Toggling the value displayed in a DIV depending on which DIV the click is performed

I have 4 (or more) DIV elements on which I want to set this behavior:

enter image description here


  1. In the beginning, all DIVs display A

  2. I click on a random DIV. It must display B. Other DIVs must keep displaying A

  3. If the consecutive click is performed on the same DIV, this later one must display back A. Others must keep displaying A.

  4. If the consecutive click is performed on a different DIV, this later one must display B. All other DIVs must display A



This is what I am working on. I have had hard time to do anything useful.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
.divElt {
margin-left: 20%;
width: 80px;
height: 40px;
background-color: blue;
color: white;
font-weight: bold;
text-align: center;
}
</style>
</head>
<body>

<script>
var data = 'B';
function funct() {
var elts = document.getElementsByClassName('divElt')
for(var i = 0; i < elts.length; i++) {
elts[i].innerHTML = data
}
}
</script>

<div class ='divElt' onclick = "funct()"> A
</div>
<br/>
<div class ='divElt' onclick = "funct()"> A
</div>
<br/>
<div class ='divElt' onclick = "funct()"> A
</div>
<br/>
<div class ='divElt' onclick = "funct()"> A
</div>
</body>
</html>


Please help me to resolve this only in JavaScript (no jQuery or other libraries). Thank you a lot in advance.

Answer

var letterA = "A";
var letterB = 'B';

//Init with all "A"
var elts = document.getElementsByClassName('divElt');
for (var i = 0; i < elts.length; i++) {
  elts[i].innerHTML = letterA;
}


function funct(item) {
  for (var i = 0; i < elts.length; i++) {
    if (elts[i] !== item)
      elts[i].innerHTML = letterA;
    else
      elts[i].innerHTML = elts[i].innerHTML === letterA ? letterB : letterA;
  }
}
.divElt {
  margin-left: 20%;
  width: 80px;
  height: 40px;
  background-color: blue;
  color: white;
  font-weight: bold;
  text-align: center;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
</head>

<body>

  <script>
  </script>

  <div class='divElt' onclick="funct(this)">
  </div>
  <br/>
  <div class='divElt' onclick="funct(this)">
  </div>
  <br/>
  <div class='divElt' onclick="funct(this)">
  </div>
  <br/>
  <div class='divElt' onclick="funct(this)">
  </div>
</body>

</html>

Comments