<h1 class="title">101<span>JS</span></h1>
<div class="container">
<h2 class="subtitle">Character Counter</h2>
<div class="content">
<p>Counts characters provided from the textarea <strong>maxlength</strong></p>
<article>
<textarea name="character-counter" cols="30" rows="10" maxlength="200"></textarea>
<i>Characters remaining: <span>200</span></i>
</article>
</div>
</div>
* {
font-family: "Montserrat", sans-serif;
}
html,
body {
margin: 0;
}
body {
background-color: #121212;
}
.title {
margin: 0;
font-family: "Press Start 2P", cursive;
display: block;
height: 60px;
font-size: 3rem;
line-height: 1.3;
text-align: center;
background: linear-gradient(to bottom, #252525 50%, darkorange 50%);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
span {
font-family: "Press Start 2P", cursive;
font-size: 1rem;
}
&:after {
content: "";
width: 100%;
height: 30px;
display: block;
background-color: darkorange;
position: absolute;
z-index: -1;
top: 0;
}
}
.subtitle {
font-family: "Press Start 2P", cursive;
font-size: 1rem;
color: #dedede;
border-bottom: 1px solid darkorange;
line-height: 2;
margin-bottom: 10px;
}
.container {
margin: 20px;
}
.content {
color: #dedede;
pre {
border: 1px solid grey;
background-color: rgba(255, 255, 255, 0.05);
padding: 10px;
}
textarea,
input[type="text"] {
border: 1px solid darkgrey;
border-radius: 5px;
padding: 5px;
background-color: rgba(255, 255, 255, 0.05);
color: #dedede;
}
}
/*
Minimal styling needed for the i element which shows the remaining characters
*/
i {
font-size: 0.8rem;
display: block;
}
View Compiled
/*
* CharacterCounter
* @param textareaEl = textarea html element
* @param remainingEl = element that includes the remaining value, updates with each event fire (keyUp)
*/
class CharacterCounter {
constructor(textareaEl, remainingEl) {
this.element = textareaEl;
this.remainingEl = remainingEl;
this.max = this.element.getAttribute("maxlength");
this.remainingChars = this.max;
this.currCounter = this.element.value.length;
this.setEvents();
}
/* calculates the remaining characters
* @param event = event triggered from event listener
*/
calc(event) {
this.remainingChars = this.element.value.length;
this.updateRemainingEl();
}
/* sets the events that will be attacked on the element
*/
setEvents() {
this.element.addEventListener("keyup", (event) => this.calc(event));
}
/* updates the remainingEl markup with the current remaining char value
*/
updateRemainingEl() {
this.remainingEl.textContent = this.max - this.remainingChars;
}
}
var textarea = document.getElementsByName("character-counter")[0];
var remaining = document.querySelector("i span");
characterCounter = new CharacterCounter(textarea, remaining);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.