Need to resize textarea when new text added by click

4317 views javascript

I'm struggling to make a textarea adjust its height if needed after some text is added to it by click. So, I use eventlistener for my textarea in order to determine when some amount of characters is added and a new line is needed further so that textarea is resized vertically. It works fine with manually added characters, but I want to use the so-called "bb-tags" as well for formatting reasons. Say, I use a button that adds red color formatting tag: [color=red][/color]. The problem is that when I add [color=red][/color] by click, my textarea won't add new lines automatically. I made the following snippet for testing my codes.

// Autoresize textarea
const textarea = document.getElementById('shoutbox-comment');

textarea.addEventListener('input', function () {
	this.rows = 2;
	this.rows = countRows(this.scrollHeight);

function countRows(scrollHeight) {
	return Math.floor(scrollHeight / 18); // 18px = line-height

// bbtags formatting
function bbtags(h, a, i) {
    var g = document.getElementById(h);
    if (g.setSelectionRange) {
        var c = g.scrollTop;
        var e = g.selectionStart;
        var f = g.selectionEnd;
        g.value = g.value.substring(0, g.selectionStart) + a + g.value.substring(g.selectionStart, g.selectionEnd) + i + g.value.substring(g.selectionEnd, g.value.length);
        g.selectionStart = e;
        g.selectionEnd = f + a.length + i.length;
        g.scrollTop = c;
    } else {
        if (document.selection && document.selection.createRange) {
            var b = document.selection.createRange();
            if (b.text != "") {
                b.text = a + b.text + i;
            } else {
                b.text = a + "REPLACE" + i;

// insert bbtag on click
bb_red.onclick = function() {
	javascript:bbtags("shoutbox-comment", "[color=red]", "[/color]");
#shoutbox-comment {
  width: 270px;
  line-height: 18px;
<script src=""></script>
<textarea id="shoutbox-comment"></textarea>
<input type="button" id="bb_red" class="bbtag-color-red" value="red">

I wonder if I need to specify something for eventlistener or else. Jquery may be used. Thank you.

answered question

1 Answer


replace code of function bb_red.onclick with this :

bb_red.onclick = function() {
    javascript:bbtags("shoutbox-comment", "[color=red]", "[/color]");
  textarea.rows = countRows(textarea.scrollHeight);

posted this

Have an answer?


Please login first before posting an answer.