Skip to content

Instantly share code, notes, and snippets.

@heiswayi
Last active December 21, 2016 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heiswayi/7b4c0940a47c7edcf8ad to your computer and use it in GitHub Desktop.
Save heiswayi/7b4c0940a47c7edcf8ad to your computer and use it in GitHub Desktop.
A JavaScript function to get which line number of caret current position belongs to in textarea element. Demo: http://jsfiddle.net/heiswayi/oxax5ouq/
function getLineOfCaret(a) {
var b = 0;
if (a.selectionEnd) b = a.selectionEnd; else if (document.selection) {
a.focus();
var c = document.selection.createRange();
if (null == c) b = 0; else {
var d = a.createTextRange(), e = d.duplicate();
d.moveToBookmark(c.getBookmark());
e.setEndPoint("EndToStart", d);
b = e.text.length;
}
}
return a.value.substr(0, b).split("\n").length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment