JSFiddle - React, Tailwind, and code Playground
by lchau
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<div class="etch-field etch-field-append etch-comment">
<textarea class="etch-comment__input" data-max-length=10 placeholder="Start typing here"></textarea>
<button type="submit" class="etch-btn etch-btn--primary add-on etch-comment__submit"><i class="etch-fa etch-fa__comment etch-fa-lg"></i></button>
<div class="etch-comment__counter">
<span class="etch-comment__max"></span> characters left
</div>
</div>
SCSS
.etch .etch-field.etch-comment {
padding: 25px 0 0;
position: relative;
}
.etch .etch-field .etch-comment__input {
box-sizing: border-box;
overflow: hidden;
word-wrap: break-word;
min-height: 60px;
width: calc(100% - 50px);
float: left;
}
.etch .etch-field .etch-comment__submit.add-on {
float: left;
height: 59px;
}
.etch .etch-field .etch-comment__counter {
font-size: 12px;
position: absolute;
right: 0;
top: 0;
color: green;
}
.etch .etch-field .etch-comment__counter--limit {
color: red;
}
JavaScript
(function() {
"use strict";
var Etch = window.Etch || {};
var commentForm = {
init: function(el) {
var $element = $(el),
maxchars = $element.data('max-length') || 500,
$counter = $element.siblings('.etch-comment__counter'),
$remaining = $counter.find('.etch-comment__max');
//autosize($element);
$remaining.text(maxchars);
$element.on('autosize:resized', function(e) {
// 20 is for the padding on the textarea
var height = $element.height() + 20;
// make sure the button keeps the same height
$element.siblings('.etch-comment__submit').height(height);
});
$element.on('input propertychange', function(e) {
var value = $element.val();
if (value.length > maxchars) {
value = value.slice(0, maxchars);
$element.val(value);
}
var remain = maxchars - value.length;
// changes color of character counter when it gets to less than 10% of max characters
if (remain <= (maxchars * 0.1)) {
$counter.addClass('etch-comment__counter--limit');
} else {
$counter.removeClass('etch-comment__counter--limit');
}
$remaining.text(remain);
});
}
};
window.Etch = _.extend(Etch, {
commentForm: commentForm
});
})();
window.Etch.commentForm.init($(".etch-comment__input"));