function setCaretPosition(element, pos, endPos) {
  if (endPos === void 0) {
    endPos = pos;
  }

  if (element.setSelectionRange) {
    element.focus();

    try {
      element.setSelectionRange(pos, endPos);
    } catch (err) {
      var elementParent = element.parentNode;
      var parentDisplayValue = elementParent.style.display;
      elementParent.style.display = 'block';
      element.setSelectionRange(pos, endPos);
      elementParent.style.display = parentDisplayValue;
    }
  } else if (element.createTextRange) {
    // IE8
    var range = element.createTextRange();
    range.collapse(true);
    range.moveEnd('character', endPos);
    range.moveStart('character', pos);
    range.select();
  }
}
Sets caret position in text input.

@author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
@param {Element} element
@param {Number} pos
@param {Number} endPos