Angular Code For Changing Input Field Background Color Partially

Test resizable

by Talha Awan

HTML

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div ng-app="inputFormatApp" ng-controller="InputFormatCtrl">
  <div class="bckg-container">
    <div class="bckg spaces" ng-style="input.leadingSpaces">
    </div>
    <div class="bckg" ng-style="input.middleContent">
    </div>
    <div class="bckg spaces" ng-style="input.trailingSpaces">
    </div>
    <br style="clear: left;" />
  </div>
  <input id="inpt" type="text" ng-model="input.text" ng-trim="false" placeholder="Add leading/trailing spaces" ng-change="inputChanged()" maxlength="20" />
</div>

CSS

.bckg-container {
  background-color: white;
  height: 18px;
  width: 170px;
}

.bckg {
  height: 18px;
  float: left;
}

.spaces {
  background-color: lightblue
}

#inpt {
  position: absolute ;
  margin-top: -20px ;
  background-color: transparent ;
  width: 170px;
  font-family: Arial;
  line-height: 13px;
  font-size: 12px;
}

JavaScript

var myApp = angular.module('inputFormatApp', [])
  .controller('InputFormatCtrl', InputFormatCtrl);

function InputFormatCtrl($scope) {
  $scope.input = {
    text: "",
    leadingSpaces: {
      'width': '0px'
    },
    middleContent: {
      'width': '170px'
    },
    trailingSpaces: {
      'width': '0px'
    }
  };
  $scope.inputChanged = function() {
    formatInputField($scope.input);
  }
}

function formatInputField(input) {
  input.leadingSpaces.width = emptySpaceWidth(input.text);
  input.middleContent.width = textWidth(input.text.trim());
  if (/\S/.test(input.text)) { //check from http://stackoverflow.com/a/2031143
    input.trailingSpaces.width = emptySpaceWidth(input.text, true);
  } else {
    input.trailingSpaces.width = 0 + "px"; //if middle content is empty all spaces should be leading
  }
}

function emptySpaceWidth(ct, reverse) {
  var content = reverse ? ct.split("").reverse().join("") : ct,
    emptySpaces = ""
  for (var i = 0; i < content.search(/\S|$/); i++) {
    emptySpaces += " "; //spaces string
  }
  return textWidth(emptySpaces);
}

// Following code taken and modified from from http://stackoverflow.com/a/15302051 & http://stackoverflow.com/a/18109656
function textWidth(text) {
  var element = $('<span>').appendTo(document.body),
    htmlText = text,
    width;
  htmlText = element.text(htmlText).html(); //encode to Html
  htmlText = htmlText.replace(/\s/g, "&nbsp;"); //replace trailing and leading spaces
  element.html(htmlText).css({
    "font-family": "Arial",
    "font-size": "12px",
    "line-height": "13px"
  });
  width = Math.ceil(element.width());
  element.remove();
  return width + 'px';
};