I'm currently trying to create a dynamic text area, though I'm facing an issue with some areas where I have to block the event from fulfilling itself, and I've come to a conclusion that I need to find out where the insertion point is in the current textarea or contenteditable divider.
I've used the events keydown
and keyup
in jQuery but they don't log when the click is made on the divider, and I wouldn't know what to look in the event
object to find what I'm after.
For example, if I'm in an empty textarea and click on the textarea, it will return 0
, since it's at the beginning - and if I were to write text it would return numbers as more characters are inserted into the textarea.
You can use selectionStart
and selectionEnd
properties from textarea
. For contenteditable
element you can use window.getSelection()
.
$('#text1').on('keyup click', function() {
console.log('Selection start :', $(this).prop('selectionStart'));
console.log('Selection end :', $(this).prop('selectionEnd'));
});
$('#text2').on('keyup click', function() {
console.log(window.getSelection().getRangeAt(0).startOffset);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text1"></textarea>
<div id="text2" contenteditable>some text</div>