Caret XY Coordinate

Get INPUT and TEXTAREA Caret XY Coordinate.

by tnhu

HTML

<input type="text" id="TEST_INPUT" onkeydown="myFunction(this)"/>
<div style="clear:both;"></div>
<textarea id="TEST_TEXTAREA" onkeyup="myFunction(this)"></textarea>

<p id="console">

</p>

JavaScript

/* Main Function
    ----------------------------------------------- */
    function myFunction(Desired_ID){
        // Extra Codes Here ETC...
        document.getElementById(Desired_ID.id).style.backgroundColor = "red";
        // Extra Codes Here ETC...
        var coordinates = getCaretCoordinates(Desired_ID, Desired_ID.selectionStart);
        var elementCoordinates = getElementCoords(Desired_ID);
	      var topPosition = coordinates.top + elementCoordinates.top;
	      var leftPosition = coordinates.left + elementCoordinates.left;
        document.getElementById('console').innerHTML = leftPosition + ", " + topPosition;
        // Extra Codes Here ETC...
    }
    
    /* Get Caret XY Coordinate
    ----------------------------------------------- */
    /* jshint browser: true */
    (function () {
    
    // The properties that we copy into a mirrored div.
    // Note that some browsers, such as Firefox,
    // do not concatenate properties, i.e. padding-top, bottom etc. -> padding,
    // so we have to do every single property specifically.
    var properties = [
      'direction',  // RTL support
      'boxSizing',
      'width',  // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does
      'height',
      'overflowX',
      'overflowY',  // copy the scrollbar for IE
    
      'borderTopWidth',
      'borderRightWidth',
      'borderBottomWidth',
      'borderLeftWidth',
      'borderStyle',
    
      'paddingTop',
      'paddingRight',
      'paddingBottom',
      'paddingLeft',
    
      // https://developer.mozilla.org/en-US/docs/Web/CSS/font
      'fontStyle',
      'fontVariant',
      'fontWeight',
      'fontStretch',
      'fontSize',
      'fontSizeAdjust',
      'lineHeight',
      'fontFamily',
    
      'textAlign',
      'textTransform',
      'textIndent',
      'textDecoration',  // might not make a difference, but better be safe
    
      'letterSpacing',
      'wordSpacing',
    
     ...