Rick Joe Rick Joe - 7 months ago 16
Javascript Question

position div below text in textarea jquery

I need to position div below the text in textarea. So if I'm typing here, the div should be in the line below and so on...

any ideas how to get this text position to place div below it?

what I did just gets the div position, not the text.

var offset = $('#comment').offset();

var x_pos = offset.left;
var y_pos = offset.top;

$("#display").css({
top: x_pos,
left: y_pos
});


html:

<textarea id=comment>how to position #display always below this text? (even if I press enter)</textarea>

<div id=display></div>


https://jsfiddle.net/krxz4ogg/

Answer

You can do it if you have a fixed height on the div which you want to appear below your textarea text.

JS expandable texarea taken from @SpYk3HH's answer.

My fiddle: https://jsfiddle.net/u2q3gw7x/

$("#MyExpandingTextArea").keyup(function(e) {
  //  this if statement checks to see if backspace or delete was pressed, if so, it resets the height of the box so it can be resized properly
  if (e.which == 8 || e.which == 46) {
    $(this).height(parseFloat($(this).css("min-height")) != 0 ? parseFloat($(this).css("min-height")) : parseFloat($(this).css("font-size")));
  }
  //  the following will help the text expand as typing takes place
  while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
    $(this).height($(this).height() + 1);
  };
});
#MyExpandingTextArea {
  padding-bottom: 6em;
  font-size: 1em;
  line-height: 1em;
}
#MovingDiv {
    border: 1px solid black;
    height: 3em;
    width: 3em;
    margin-top: -4em;
    margin-left: 10px;
    position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea name="myTextArea" id="MyExpandingTextArea"></textarea>
<div id="MovingDiv">
  &nbsp;
</div>

If you do not want the effect of the entire textarea expanding, consider wrapping the text area in a div with a fixed height and overflow: hidden;

Comments