Imran Imran - 9 months ago 41
CSS Question

Adding different CSS for space and text to an text type input

I have an

text
type input in an html form as bellow:

<input type="text" id="tag" name="tag">


Now, I want to add style on that input text based on user's input. This style need to be different for
text
and
space
.

For example: if someone enters
php java python
in the input field then I want to style
php
,
java
and
python
with specific background where their
internal spaces
will have different background.

Is it possible? If possible then how?

Answer Source

The answer is yes and no. Yes it is possible, but it is not possible with input only.

You cannot put elements inside input tags, but You could have some kind of container which would handle this part for You.

I've attached very simple and naive example, it could be done way better, but it shows You the concept.

Text inside input is being split by space, and new element for each word and space is created.

You could do something like that, but with styled input inside container. Then You should listen for input change. When user press space, You should get the word which user wrote, create new element for word (and also one more for space), append it to container, and clear the input, so it would be ready for next, new word.

const textContainer = document.querySelector('#textContainer')

document.querySelector('#myInput').addEventListener('input', ({ target }) => textToElements(target.value))

const textToElements = (text) => {
  const words = text.split(' ')
  const wordsElements = words.map(createWordElement)
 
  clearWordsContainer()
  wordsElements.forEach(putWordElement)
}

const createWordElement = (word) => {
  const element = document.createElement('span')

  element.classList.add('word')
  element.textContent = word

  return element
}

const putWordElement = (element) => {
  const spaceElement = document.createElement('span')

  spaceElement.classList.add('space')
  spaceElement.textContent = ' '

  textContainer.appendChild(element)
  textContainer.appendChild(spaceElement)
}

const clearWordsContainer = () => textContainer.innerHTML = ''
.word {
  color: #FFF;
  background: #333;
}

.space {
  background: #999;
}
<div class="container">
  <div id="textContainer"></div>
  <input id="myInput" type="text" />
</div>