Restart the count if you exceed the options

0

This question will probably be answered in less than 5 minutes from so easy, but I'm breaking my head ...

I'll simplify a lot here, but I think you can understand:

I create elements by javascript, each has its background color, there are 8 colors that are in classes. (.1 background, .2 background ...).

But it's only 8 colors, how do I create more than 8 elements to count back to 0?

asked by anonymous 06.08.2018 / 19:33

3 answers

1

If you do not want colors exactly in that order, you can generate a random value between 1 and 8:

$(function(){
  $("#adicionar").on("click",function(e){
  var num = Math.floor((Math.random() * 8) + 1);
    $("#teste").append("<div class='fundo"+ num +"'></div>");
    e.preventDefault();
  });
});
#teste div{
  float:left;
  clear: left;
  width:40px;
  height: 40px;
  margin: 2px;
}
.fundo1{
  background-color: #000;
}
.fundo2{
  background-color: #00F;
}
.fundo3{
  background-color: #0FF;
}
.fundo4{
  background-color: #F00;
}
.fundo5{
  background-color: #FF0;
}
.fundo6{
  background-color: #FA0;
}
.fundo7{
  background-color: #0F0;
}
.fundo8{
  background-color: #F0F;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste">
</div>
<a href="#" id="adicionar">Adicionar</a>
    
06.08.2018 / 19:51
0
$(function(){
  //cria uma variavel para saber qual a contagem
  var contador = 0;
  $("#adicionar").on("click",function(e){
    // alimenta + 1 na variável;
    contador ++;
    // se ela for mais que 8, volta a ter o valor 1
    if(contador > 8){
      contador = 1;
    }
    $("#teste").append("<div class='fundo" + contador + "'></div>");
    e.preventDefault();
  });
});
    
06.08.2018 / 19:39
0

So, I just remembered how to do it, I apologize for taking your time.

Just use%, in case:

var num=NUMERO_ATUAL % MÁXIMO;

This will keep within my maximum range. So following my example:

$(function(){
  $("#adicionar").on("click",function(e){
    $("#teste").append("<div class='fundo"+ (($("#teste div").length % 8)+1) +"'></div>");
    e.preventDefault();
  });
});
#teste div{
  float:left;
  clear: left;
  width:40px;
  height: 40px;
  margin: 2px;
}
.fundo1{
  background-color: #000;
}
.fundo2{
  background-color: #00F;
}
.fundo3{
  background-color: #0FF;
}
.fundo4{
  background-color: #F00;
}
.fundo5{
  background-color: #FF0;
}
.fundo6{
  background-color: #FA0;
}
.fundo7{
  background-color: #0F0;
}
.fundo8{
  background-color: #F0F;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="teste">
</div>
<a href="#" id="adicionar">Adicionar</a>
    
06.08.2018 / 19:44