Change text in different colors when typing

I print a text box that gives consistent data, then changes the color of the text and enters a second time, then changes a different color, then types again, and then changes the color.

+4
source share
1 answer

Bind an event handler to a text field using , and inside the event handler, changes the color from the array input on()

var color = ['red', 'yellow', 'red', 'blue', 'brown'];
var i = 0;
$('#text').on('input',function() {
  $(this).css('color', color[i]);
  i = (i + 1) % color.length;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="text"/>
Run codeHide result

Or create a random color code using Math.random()

var color = ['red', 'yellow', 'red', 'blue', 'brown'];
$('#text').on('input', function() {
  $(this).css('color', "#" + (Math.random() * 16777215 | 0).toString(16));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="text" />
Run codeHide result
+3
source

Source: https://habr.com/ru/post/1616845/


All Articles