Get cursor position & selection of input field

getSelection() selectionStart

by Shantanu Kulkarni

HTML

<html>
    <head>
    <script>
      function f1(el) {
        var val = el.value;
        console.log(window.getSelection().toString());
        console.log(val.slice(0, el.selectionStart).length);
    	}
    </script>
    </head>
    <body>
    <input type=text id=t1 value=abcd>
        <button onclick="f1(document.getElementById('t1'))">check position</button>
    </body>
    </html>