1

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:

  1. Calculating in which row user is (based on font size, text area width and characters count in that text area).

  2. 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

GalAbra
  • 5,048
  • 4
  • 23
  • 42
Joelty
  • 1,751
  • 5
  • 22
  • 64
  • What's wrong with the algorithms you've suggested? – GalAbra Jul 11 '19 at 09:29
  • @GalAbra I don't there's something wrong with it (except it may be tricky with "weird" characters) but I thought that it's already built in e.g in browser because it has to display those characters somehow... – Joelty Jul 11 '19 at 09:31
  • Then you have an alternative solution in the post you've attached. It still works, 10 years later ;) – GalAbra Jul 11 '19 at 09:34
  • Having played around with the `cols` property, I think the 10 year old solution is the best way to go. – Matt Ellen Jul 11 '19 at 10:50

1 Answers1

1

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>
Joelty
  • 1,751
  • 5
  • 22
  • 64