Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why my array won't back to 0 (javascript)?

var a = ["red", "blue", "green"];
var i = 0
$(".button").click(function() {
  i++;
  if (i >= 3) {
    i = 0;
  }
  console.log(i);
  $("body").addClass(a[i]);
  console.log(a[i]);
});
.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="button">Click</button>

It can turn from white to blue and green, but if i click the button again it won’t turn to red, blue, and green. But the console show 1,2,0,1,2,0 and also the color blue, green, red, blue

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your issue is that you’re not ever removing the old class, so eventually the body has all three classes and it just uses the last one. Add

$("body").removeClass(a[i]);

to the beginning of your click handler:

var a = ["red", "blue", "green"];
var i = 0
$(".button").click(function() {
  $("body").removeClass(a[i]);
  i++;
  if (i >= 3) {
    i = 0;
  }
  console.log(i);
  $("body").addClass(a[i]);
  console.log(a[i]);
});
.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.green {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <button type="button" class="button">Click</button>
</body>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading