Find out the ‘line’ (row) number of the cursor in a textarea

You would want to use selectionStart to do this.

<textarea onkeyup="getLineNumber(this, document.getElementById('lineNo'));" onmouseup="this.onkeyup();"></textarea>
<div id="lineNo"></div>

<script>

    function getLineNumber(textarea, indicator) {

        indicator.innerHTML = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
    }

</script>

This works when you change the cursor position using the mouse as well.

Leave a Comment