Skip to content

Instantly share code, notes, and snippets.

@chrisdavies
Last active April 6, 2018 15:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisdavies/4ea650aba4b0a5737f91 to your computer and use it in GitHub Desktop.
Save chrisdavies/4ea650aba4b0a5737f91 to your computer and use it in GitHub Desktop.
Example of how to get an autosized textarea working in Vue.js

Autosize Textarea

I seem to implement this feature in just about every project, and I never seem to be able to find my old implementations easily enough. So, here's a gist. Should help to get things started.

JS

Using Vue:

// Autosize textarea directive
Vue.component('autosize-textarea', {
  template: '<div class="autosize-textarea"><textarea v-model="val" autocomplete="off"></textarea><pre>{{val}} \n \n</pre></div>',
});

Using jQuery:

$('.autosize-textarea').each(function () {
  $(this).on('input, keyup', function () {
    $(this).find('pre').text($(this).find('textarea').val() + '\n\n');
  });
});

CSS

/* Autosize */
.autosize-textarea {
  position: relative;
  border: 0;
  padding: 0.1em;
}

.autosize-textarea pre,
.autosize-textarea textarea {
  border: 0;
  padding: 0;
  font-size: 1em;
  word-wrap: break-word;
  text-wrap: normal;
  white-space: pre-wrap;
  font-family: inherit;
  line-height: 1.4em;
  resize: none;
  min-height: 3em;
  display: block;
}

.autosize-textarea textarea {
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.autosize-textarea pre {
  visibility: hidden;
}
@chrisburton
Copy link

Hey, Chris. I stumbled upon this gist of yours. I'm quite new to Vue.js and I couldn't seem to get this example working on CodePen. Perhaps you could take a look?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment