Reputation: 2009
I want to display something e.g div under text area where user typing
I managed to obtain where he's currently typing via selectionStart/End
, but how can I actually calculate coordinates (x,y) of his cursor?
I suppose there are other ways of achieving that than these two:
Calculating in which row user is (based on font size, text area width and characters count in that text area).
x as textarea.X + selectionStart
in this row
y as textarea.Y + rows * font size
I found this, but it is almost 10 years old
Upvotes: 1
Views: 1184
Reputation: 2009
https://github.com/Codecademy/textarea-helper
$('textarea').on('keyup paste cut mouseup', function () {
// Get the textarea's content height.
var contentHeight = $(this).textareaHelper('height')
// Set the textarea to the content height. i.e. expand as we type.
$(this).height(contentHeight);
// Follow the caret arounbd.
$('.tail').css(
$(this).textareaHelper('caretPos')
);
});
// Call it manually at first.
$('textarea').keyup();
.tail {
background: red;
width: 50px;
min-height: 50px;
position: absolute;
}
textarea {
width: 250pxpx;
min-height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://rawgit.com/Codecademy/textarea-helper/master/textarea-helper.js"></script>
<textarea></textarea>
<div class="tail"></div>
Upvotes: 1