How to change background color according to value

Asked

Viewed 384 times

1

I built a script to count characters from a textarea in Javascript, the code is this:

<div>
    <p class="texto-cont">Restam <span id="cont">2.200</span> caracteres</p>
</div>

function limite_textarea(valor) {
    quant = 2200;
    total = valor.length;
    if(total <= quant) {
        resto = quant - total;
        document.getElementById("cont").innerHTML = resto;
    } else {
        document.getElementById("texto").value = valor.substr(0,quant);
    }
}

I need to change the background of the stretch "2,200 characters remain". When it’s at 2,200 I’d like you to background turned green, orange in 2000 and red in 100 characters.

  • Have you tried document.getElementById("cont").style.backgroundColor = "red" ?

  • How could I apply in this case?

1 answer

4


Just use a if or ternary operation and use the property element.style.backgroundColor.

Example:

/**
 * Captura os elementos
 */
const content = document.querySelector("#content")
const count = document.querySelector("#count")

/**
 * Utiliza o evento "input" para detectar novas alterações no textarea
 */
content.addEventListener("input", () => {

  /**
   * Captura o valor do atributo "maxlength" e 
   * calcula a quantidade restantes de caracteres
   */
  let maxLength = parseInt(content.getAttribute('maxlength'))
  let charRemaining = maxLength - content.value.length
  
  /* Converte o valor para pt-BR (Adiciona o "." em caso de milhar) */
  count.textContent = charRemaining.toLocaleString()
  
  /**
   * Utiliza uma operação ternária para verificar a quantidade de caracteres restantes
   * Se a qnt. restante for maior que 2190 => Verde, caso contrário realiza outra opção ternária
   * Se a qnt. restante for maior que 2180 e menor que 2190 => Laranja, caso contrário utiliza o vermelho
   */
  count.style.color = charRemaining > 2190 ? 'green' : charRemaining > 2180 ? 'orange' : 'red'
  content.style.backgroundColor = charRemaining > 2190 ? '#00800026' : charRemaining > 2180 ? '#ffa50026' : '#ff000026'
})

content.dispatchEvent(new Event("input"))
<div>
  <textarea id="content" rows="10" maxlength="2200"></textarea>
	<p class="texto-cont">Restam <span id="count"></span> caracteres</p>
</div>


If you use any plugin for WYSIWYG or similar, it is necessary that this allows you to "listen" to some events such as keydown, keyup, input etc. This will not always happen. In the example below, I will use the project emojionearea, but may not work with others.

Example commenting:

const maxLength = 2200
const emojionearea = $("#emojionearea1").emojioneArea({
  events: {
    /**
     * Informa a função callback do evento `keyup`
     * Caso queira utilizar outro evento, basta dá
     * uma olhada na documentação:
     * https://github.com/mervick/emojionearea#events
     */
    keyup: (editor) => { charRemaining(editor[0]) }
  }
})


function charRemaining(editor) {
  /**
   * Captura o valor do atributo "maxlength" e 
   * calcula a quantidade restantes de caracteres
   */
  let charRemaining = maxLength - editor.textContent.length

  /* Converte o valor para pt-BR (Adiciona o "." em caso de milhar) */
  count.textContent = charRemaining.toLocaleString()

  /**
   * Utiliza uma operação ternária para verificar a quantidade de caracteres restantes
   * Se a qnt. restante for maior que 2190 => Verde, caso contrário realiza outra opção ternária
   * Se a qnt. restante for maior que 2180 e menor que 2190 => Laranja, caso contrário utiliza o vermelho
   */
  count.style.color = charRemaining > 2190 ? 'green' : charRemaining > 2180 ? 'orange' : 'red'
  count.style.backgroundColor = charRemaining > 2190 ? '#00800026' : charRemaining > 2180 ? '#ffa50026' : '#ff000026'
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/emojionearea/3.4.1/emojionearea.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/emojionearea/3.4.1/emojionearea.min.css" rel="stylesheet"/>

<div class="row">
  <div class="span6">
    <textarea id="emojionearea1"></textarea>
  </div>
  
  <p class="texto-cont">Restam <span id="count">2.200</span> caracteres</p>
</div>

  • It worked on localhost, but when I implemented the code on my site, it didn’t work, the server failed the const statement. I changed it to var. then the code managed to display the characters, but stopped counting and changing the background.

  • My code is with the input code, but the text area field is represented by a div, then the count is not done, because the data entry is being done in div. The div code only appears when I open the page, in the php code it does not appear, so I cannot define the div class and declare in javascript. How do I solve?

  • @Rodrigo, you’re wearing a div with the property contenteditable, is that it? If it is, just do it this way: https://codepen.io/valdeir2000/pen/LgMXeX?editors=1010

  • The mistake with const may have been generated due to browser version, for greater compatibility you can use the BabelJs

  • Valdeir, div is contenteditable yes, but it already has a div class defined, and I can’t find the file where that code is. In the codepen the code you reported worked, but since I can’t find the code to declare maxlength in the div, I declared it in the code, thus: https://codepen.io/rodson-rodrigo/pen/dgabNR You’ll see that it works, but when I enter it on my website, it does not work, and in the debugger appears the error Uncaught Typeerror: Cannot read Property 'setAttribute' of Undefined at

  • @Rodrigo , the error happens because the div was not found (case to div be in a iframe, you will not be able to access it). In this case you can define a constant with the maximum value: https://codepen.io/valdeir2000/pen/yRZBoB

  • Now the error is gone, but it still does not count, and presenting the error Uncaught Typeerror: Cannot read Property 'addeventlistener' of null al

  • Just to help, I wish to do it in the emojionearea.

  • @Rodrigo Important information. I updated the answer.

  • Good afternoon, I ended up not running this update, by chance I did today and it worked. I would now just like to change the whole background of the class. "Left xxx characters" text-cont as the number of characters decreases.

Show 5 more comments

Browser other questions tagged

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