Show remaining characters in textarea using amp-bind
AMP is awesome! Look at this. So easy to code. It reminds me of Vue.
Type something in the text area below:
To do it, first get the required script in the head.
<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async custom-element="amp-bind"
src="https://cdn.ampproject.org/v0/amp-bind-0.1.js">
</script>
Create a simple <textarea> element. Bind values to a variable such as maxlength attribute. Use the on attribute to save the character count of the text area to a variable. We will use input-throttled because we want the value to update on every key input.
<textarea maxlength="20"
on="input-throttled:AMP.setState({
length: event.value.length,
maxlength: 20 })">
</textarea>
Now length is saved. Let’s create a macro to calculate the remaining characters.
<amp-bind-macro id="textCounter"
arguments="length, maxlength"
expression="maxlength - length" />
id is the name of the function. arguments are the values it will take. And expression is the formula.
Finally, we get to display the result of the expression on input. Call the textCounter macro to get the value of [text] which is the innerText of the DOM element.
<span hidden [hidden]="length < 1"
[text]="textCounter(length, maxlength)">
</span>
Optionally, I have used the [hidden] attribute to hide the element if the input is empty or, in other words, when there is zero characters in the text area.
WOW! ⚡ is 😻
-- end --