JavaScript 文字数チェック

入力文字数をkeyupによるthis.value.lengthで取得し、条件分岐で、CSSの要素を変える処理を作ります。

html

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comment</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
        <div class="container">
            <textarea id="comment" placeholder="your comment here"></textarea>
            <div class="btn">Submimt</div>
            <p><span id="label"></span> characters left</p>
            
      <script src="myscript.js">
      </script>
  </body>
</html>

styles.css

@charset "utf-8";

body {
	font-family: Verdana, sans-serif;
	font-size: 16px;
	background: #e0e0e0;
}

.container {
	width: 400px;
	margin: 30px auto;
}

textarea {
	width: 400px;
	box-sizing: border-box;
	height: 200px;
	padding: 14px;
	font-size: 16px;
	border: none;
	border-radius: 5px;
	margin-bottom: 14px;
	line-height: 1.5;
}
textarea:focus {
	outline: none;
}

p {
	color: #333;
	font-size: 14px;
	margin: 0;
	padding-top:8px;
}

#label{
	font-weight: bold;
}

.btn {
	display: inline-block;
	width: 150px;
	background: #00aaff;
	padding: 5px;
	color: #fff;
	border-radius: 5px;
	text-align: center;
	cursor: pointer;
	box-shadow: 0 4px 0 #0088cc;
	float: right;
}

.warning {
	color:red;
}

myscript.js

(function(){
		'use strict';

		var comment = document.getElementById('comment');
		var label = document.getElementById('label');

		var LIMIT = 20;
		var WARNING = 10;

		label.innerHTML = LIMIT;

		comment.addEventListener('keyup', function(){
				var remaining = LIMIT - this.value.length;
				label.innerHTML = remaining;
				if (remaining < WARNING){
					label.className = 'warning';
				} else {
					label.className = '';
				}
		});
})();

%e7%84%a1%e9%a1%8c