S Shane
S Shane

Reputation: 47

How to change the font color of an user input value (prompt) in JavaScript?

How can I change the color of the value of the variable number (nb)? How can I change the font color of an user input value (prompt) in JavaScript?


<html>
    <head>
        <style>
            #block{
                color: white;
                width: 300px;
                height: 60px;
                background-color: #2b2e2e;
                text-align: center;
                padding-top: 30px;
            }
        </style>
    </head>
    <body>
        <div id="block">
            
        </div>
        <script>
            window.onload = function printNumber(){
                var unBlock = document.getElementById("block");
                var nb = Number(prompt("Saisir un nombre: "));
                
                if(nb == null || nb == ""){
                    unBlock.innerHTML = "No input number.";
                }else{
                    unBlock.innerHTML = "Your input number is "+nb;
                }
                
            }
        </script>
    </body>
</html>

Upvotes: 0

Views: 926

Answers (1)

Marc
Marc

Reputation: 11623

The code below illustrates two ways.

  1. By creating a span with colored as its class, it turns it blue.
  2. Subsequently, in my code, I'm overriding that by turning it red using javascript.

Either of those methods will work, but you only need one, not both. I used both just for illustration of your options.

window.onload = function printNumber() {
  var unBlock = document.getElementById("block");
  var nb = Number(prompt("Saisir un nombre: "));

  if (nb == null || nb == "") {
    unBlock.innerHTML = "No input number.";
  } else {
    unBlock.innerHTML = `Your input number is <span class='colored'>${nb}</span>`;
    //the next line will select your span and override blue with red.
    document.querySelector("span.colored").style.color = 'red';
  }

}
#block {
  color: white;
  width: 300px;
  height: 60px;
  background-color: #2b2e2e;
  text-align: center;
  padding-top: 30px;
}

span.colored {
  color: blue;
}
<div id="block">
</div>

Upvotes: 2

Related Questions