Character Counter
Character Counter is a small jQuery plugin for inputs and textareas to count characters in it.
by kakss
HTML
<label>textarea:</label>
<textarea class="char-counter"></textarea>
<label>input:</label>
<input class="char-counter" type="text">
<label>default value:</label>
<input class="char-counter" type="text" value="Hello world!">
<label>unlimited textarea:</label>
<textarea class="unlimited-char-counter"></textarea>
CSS
textarea {
width:400px;
height:200px;
}
input {
width:400px;
height:50px;
font-size: 16px
}
label {
display:block;
clear: both;
padding: 10px 0;
}
div.focus-textarea span
{
z-index: 999;
position: absolute;
border-width: 1px;
border-style: solid;
border-radius: 3px;
background-color: #ffffe0;
border-color: #e6db55;
color: #000;
clear: both;
padding: 0 4px;
margin: 0.5px 0 6px 0;
font-family: -system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";
font-weight: 600;
}
JavaScript
(function ($) {
"use strict";
$.fn.charCounter = function (options) {
if (typeof String.prototype.format == "undefined") {
String.prototype.format = function () {
var content = this;
for (var i = 0; i < arguments.length; i++) {
var replacement = '{' + i + '}';
content = content.replace(replacement, arguments[i]);
}
return content;
};
}
var options = $.extend({
backgroundColor: "#FFFFFF",
position: {
right: 10,
top: 10
},
font: Â {
size: 12,
color: "#000"
},
limit: 255
}, options);
return this.each(function () {
var el = $(this),
wrapper = $("<div/>").addClass('focus-textarea').css({
"position": "relative",
"display": "inline-block"
}),
label = $("<span/>").css({
"zIndex": 999,
"backgroundColor": options.backgroundColor,
"position": "absolute",
"font-size": options.font.size,
"color": options.font.color
}).css(options.position);
if(options.limit > 0){
label.text("{0}/{1}".format(el.val().length, options.limit));
el.prop("maxlength", options.limit);
}else{
label.text(el.val().length);
}
el.wrap(wrapper);
el.before(label);
el.on("keyup", updateLabel)
.on("keypress", updateLabel)
.on('keydown', updateLabel);
function updateLabel(e) {
if(options.limit > 0){
label.text("{0}/{1}".format($(this).val().length,...