addClass with Math.round

Asked

Viewed 31 times

0

I’m trying to make a script in which when a sensor that is part of the test sends me a number 5, it changes the color of the table that is red to green. That way the test would be approved.

However I am not able to connect addClass with Math.round and make it work both, other doubt, in "mouseenter" would have to be an automatic reading function, and not an event, I looked for something like and found nothing.

$(function(){
    $('#sensorValor').mouseenter(function () {
        roundedValue = Math.round(parseFloat(sensorValor) *100 / 100;
        if((roundedValue >=5) && testEnable){
          $('sensorValor').addClass('bad_3');
        })
    });


.bad_3{
 border: 10px solid green;
}
  • Missing a closing parenthesis in Math.round function

  • Thanks but it still didn’t work

1 answer

1


I made an example of code according to your question with 2 options, clicking a button and passing value and when you put the mouse over the div generates a random code. According to this code is done the test proposed in your example and if true, add or remove the classes according to need. See if he answers you.

$(function() {

  var sensor = 0,
    testEnable = true;

  window.teste = function teste(value) {

    if (value != undefined) {
      sensor = Number(value);
    } else {
      sensor = geraNumeroAleatorio();
      console.log("Número aleatório gerado: %s", sensor);
    }

    if ((sensor >= 5) && testEnable) {
      $("#trocaCorSensor").removeClass('yellow').addClass('green');
    } else {
      $("#trocaCorSensor").addClass('yellow').removeClass('green');
    }
  }

  function geraNumeroAleatorio() {
    return Math.round(Math.random() * 10)
  }

});
.yellow {
  background-color: yellow;
}

.green {
  background-color: green;
}

button {
  min-width: 120px;
  padding: 5px;
  margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="trocaCorSensor" onmouseover="teste()">
  <p>Conteúdo...</p>
</div>

<button class="yellow" onClick="teste(1)">Teste Valor 1</button>
<button class="yellow" onClick="teste(2)">Teste Valor 2</button>
<button class="yellow" onClick="teste(3)">Teste Valor 3</button>
<button class="yellow" onClick="teste(4)">Teste Valor 4</button>
<button class="green" onClick="teste(5)">Teste Valor 5</button>
<button class="green" onClick="teste(6)">Teste Valor 6</button>
<button class="green" onClick="teste(7)">Teste Valor 7</button>
<button class="green" onClick="teste(8)">Teste Valor 8</button>
<button class="green" onClick="teste(9)">Teste Valor 9</button>
<button class="green" onClick="teste(10)">Teste Valor 10</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.