Unique CSS styles for "+" and "-" when user types in input

Issue

When the user types in + in my input, I would like the + to be green

Ex: +10000 –> "+" should be green and 10000 should be black

When the user types in - in my input, I would like the - to be red

Ex: -10000 –> "-" should be red and 10000 should be black

My idea was to use ::first-letter, but I realize it doesn’t work on input

Is this possible at all with css and javascript? Do I need some fancy Regex to accomplish this?

input {
  font-size: 100px;
}

/* only - should be red */
input::first-letter {
  color: red;
}

/* only + should be green */
input::first-letter {
  color: green;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="styles.css" />
    <title>Static Template</title>
  </head>
  <body>
    <input type="text" />
  </body>
</html>

Solution

First get the <input> element with .getElementsByTagName('input')[0], then you can attach an event listener on keyup. From here, you can use .style.color to update the color based on .value[0]:

const target = document.getElementsByTagName('input')[0];
target.addEventListener('keyup', function() {
  if (this.value[0] === '-') {
    this.style.color = 'red';
  }
  else if (this.value[0] === '+') {
    this.style.color = 'green';
  }
  else {
    this.style.color = 'black';
  }
})
input {
  font-size: 100px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="styles.css" />
  <title>Static Template</title>
</head>

<body>
  <input type="text" />
</body>

</html>

Note that the above snippet only checks the first character inputted. If you want to check for any occurrence of the target character, you can loop over the .value.

Answered By – Obsidian Age

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published