7 814 Form / Codepen

Textarea auto height

Скрипт для авто подстройки высоты тега формы textarea в зависимости от вводимого внутри текста


HTML

<textarea rows="1">Here is a very long value for testing auto height</textarea>

SCSS

textarea {
    resize: none;
    &.auto {
        overflow-y: hidden;
    }
}

// Some styles
textarea {
    -webkit-appearance: none;
    box-sizing: border-box;
    outline: none;
    width: 100%;
    max-width: 240px;
    font-size: 14px;
    font-family: 'Inter';
    line-height: 22px;
    padding: 16px 20px;
    border-radius: 15px;
    color: #404660;
    border: none;
    background: #fff;
    transition: box-shadow .25s;
    box-shadow: inset 0 0 0 1px var(--border-color, #E1E6F9), 0 0 0 3px var(--focus-color, transparent);
    &:focus {
       --focus-color: #ECEFFC;
    }
    &:focus,
    &:hover {
        --border-color: #BBC1E1;
    }
}

JS

document.querySelectorAll('textarea').forEach(el => {
    el.style.height = el.setAttribute('style', 'height: ' + el.scrollHeight + 'px');
    el.classList.add('auto');
    el.addEventListener('input', e => {
        el.style.height = 'auto';
        el.style.height = (el.scrollHeight) + 'px';
    });
});

Комментарии

  • Facebook
  • Вконтакте

Похожие статьи