Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

jQuery - detect cut / paste with textarea auto-expand function

I have a function that auto-expands the textarea width and height however when I cut or paste the textarea value, the auto-expand function doesn't fire. How do I bind the resize function to detect when I paste in or cut away text?

$(document).ready(function() {
  var $inputs = $(".expandable");

  function resizeForText(text) {
    var $this = $(this);
    if (!text.trim()) {
      text = $this.attr("placeholder").trim();
    var $span = $this.parent().find("span");
    var $inputSize = $span.outerWidth(true);
    $this.css("width", $inputSize);

  $inputs.find("textarea").keypress(function(e) {
    if (e.which && e.charCode) {
      var c = String.fromCharCode(e.keyCode | e.charCode);
      var $this = $(this);
      resizeForText.call($this, $this.val() + c);

  // Backspace event only fires for keyup
  $inputs.find("textarea").keyup(function(e) {
    if (e.keyCode === 8 || e.keyCode === 46) {
      resizeForText.call($(this), $(this).val());

  $inputs.find("textarea").each(function() {
    var $this = $(this);
    resizeForText.call($this, $this.val());
  var textarea = $("textarea");
  textarea.on("input", function() {
    $(this).css("height", ""); //reset the height
    $(this).css("height", Math.min($(this).prop("scrollHeight")));
textarea {
  resize: none;
  overflow: hidden;
  max-width: 200px;
  padding: .9rem;
  border: 1px solid #ededed;
  border-radius: 6px;

.expandable span {
  display: none;
  margin: 0 12px;

.measure {
  width: 200px;
  background: #ececec;
  text-align: center;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="measure">200px</div>
<div class="expandable">
  <textarea type="text" rows="1" class="textarea" placeholder="Placeholder" autocomplete="off"></textarea>

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share