-1

We are working on applying css to a textfield in AngularJS, we want to add colors to substrings of text dynamically when user type something in the textarea. We are able to find the substrings which are to be formated with colors in textarea, but unable to add css to those substrings.

We are able to solve that issue in but not able to get the same result in

Heri
  • 4,368
  • 1
  • 31
  • 51

1 Answers1

0

You can not add CSS to specific areas of a single text block. Instead you would need to convert the string into a set of tags.

Here is some generic code that will do, I hope, what you are looking for:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h4>Type your text in here:</h4>
    <textarea id="one" style="width: 400px;height: 200px;font: 14px tahoma;" autofocus>The cow, bird and frog jumped out the window</textarea>
    <hr/>
    <h4>The colored output displayes here:</h4>
    <output id="out"></output>
    <script>
    var keyWords = {
      'frog': '#33FF33',
      'cow': '#DDDD33',
      'bird': '#9999FF',
      'window': '#FF3333'
    };

    var keyWordRegEx = new RegExp(Object.keys(keyWords).join('|'), 'gi');

    function onInputHandler() {
      var str = ta.value.replace(keyWordRegEx, function(keyWord) {
        return '<span style="padding: 0 2px;background-color:'+keyWords[keyWord.toLowerCase()]+'">'+keyWord+'</span>';
      });
      o.innerHTML = str;
    }

    var ta = document.getElementById('one');
    var o = document.getElementById('out');
    ta.addEventListener('input', onInputHandler);
    onInputHandler();
    </script>
  </body>
</html>

The magic happens with the .replace function. It uses Regular Expressions to look up any of the key words and replaces the words with a <span> tag that includes the desired background color.

This code can be adjusted to work with Angular or any other library or framework.

Intervalia
  • 10,248
  • 2
  • 30
  • 60