How can I style text input as I type?

Each time I enter a character in the input field, I parse the expression so as to get:

  • Array of tokens i.e. tokenArray = [2, *, COS, (, 4,)]
  • The corresponding array of token types, i.e. tokenType = [NUMBER, OPERATOR, FUNCTION, (, NUMBER,)]

I need to style each token (for example, assigning a different color to each token) based on its corresponding type of token.

I was able to easily create a dynamic copy of the input text in another <div> (and not in the input text that I ask for help) as follows:

JavaScript:

 function processExpression() { var userInput = document.getElementById('inputText').value; var resultOutput = parse(userInput); //this generates the two arrays described above for (i in tokenArray) newHTML += "<span style='color: " + colorMap[ tokenType[i] ] + " '>" + tokenArray[i] + "</span>"; document.getElementById('styledExpression').innerHTML = newHTML; } 

HTML:

 <input type="text" id="inputText" value="" placeholder="Type expression" size="40" onKeyDown="processExpression();" onKeyUp="processExpression();"/> <div id="styledExpression" value=""></div> 

How to style input text directly in the input field where I type? Any javascript solution?

UPDATE

Tim's answer to the question of replacing innerHTML in a contenteditable div gives some useful help.

How would you modify http://jsfiddle.net/2rTA5/2/ to decide when, each time you click on a key, one repeats the entire editable one? For example, imagine that you enter "= if (AND (3 = 2, A1: A4, OR (0,1)), 5,6)", and each time you press the key, the edited program code is overwritten (see), and i'm losing the cursor.

How can this solution ignore the type of token or symbol or node and just save and restore the absolute pointer (from the beginning) that was before the key was pressed?

+7
source share
3 answers

Text inputs do not support stylized content. The end of the story.

A common solution is to use contenteditable .

+6
source

as Matt said, <input> don't support the look and feel. However, one possible solution would be to use a second <span> , which will contain the input value, and show the stylized content here. If this is unacceptable, use contenteditable , as Matt suggested.

+4
source

You may look as if it was unimportant aesthetics.

  • Make the background and text <input> transparent
  • Behind him is <span>
  • Refresh the contents of the <span> (with the appropriate style) when the contents of the <input> change

Here is a quick demo.

+2
source

All Articles