0

I have a chat application using jquery, I want to when someone typing a long string justify it inside of the input as all chat do, can someone help me thanks in advance enter image description here

2 Answers2

1

Ensure you are using a textarea with specified width/columns for your message entry. Inputs are not suitable for what you are asking for.

0

You should use a text area. If you want the rows to dynamically adjust, you can use the jQuery autosize plugin.

The demo below uses Typed to automagically type into the text area and Lorem.js to generate the text. I added a watch function (updateFn) to check to see if the text area needed to be expanded because automated input does not act the same as physical user input. ;)

var updateRate = 100;
var updateId = null;

(function($) {
  $.fn.numOfLines = function() {
    var lineHeight = parseInt(this.css('lineHeight'), 10);
    return Math.floor(this.attr('scrollHeight') / lineHeight);
  }
})(jQuery);


$(function() {
  $('.auto-size').autosize();
  var typed = new Typed('.auto-size', {
    strings: [ new Lorem().createText(2, Lorem.TYPE.PARAGRAPH) ],
    typeSpeed: 1000 / updateRate,
    preStringTyped: startUpdate,
    onComplete: cancelUpdate
  });
});

function updateFn(opts) {
  var lines = $('.auto-size').numOfLines();
  if (lines != opts.prevLines) {
    opts.prevLines = lines;
    $('.auto-size').trigger('autosize.resize');
  }
}

function startUpdate(arrayPos, self) {
  updateId = setInterval(updateFn, updateRate, { prevLines: 1 });
}

function cancelUpdate(self) {
  clearInterval(updateId);
}
textarea[class="auto-size"] {
  resize: none;
  word-break: break-word;
  text-wrap: unrestricted;
}
.input-container label {
  font-weight: bold;
  vertical-align: top;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-autosize@1.18.18/jquery.autosize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.9/typed.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/f/loremjs@ec971d2c7fc9a9b6a788095e0523a2794420f5c4/lorem.js"></script>
<div class="input-container">
  <label>Message: </label>
  <textarea cols="72" rows="1" class="auto-size"></textarea>
</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132