2.0.0 • Published 10 days ago

input-length v2.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 days ago

Input Length

This component creates a visual representation of the maxlength constraint and updates it as the user interacts with that field, with customisation to allow custom classes and styling.

text

Installation

npm install input-length

Basic usage

<label for="example">Example field</label>
<input type="text" id="example" class="js-inputLengthWarning" maxlength="4" />
const $ = require('jquery');

import InputLength from './dist/InputLength';

$(function () {
    const inputLength = new InputLength($('html'));

    inputLength.init({
      targetSelector: '.js-inputLengthWarning'
    });
});

A new element will be inserted immediately after the target input, and new attributes will be added. The aria-describedby guid will be added to the existing aria-describedy value if one is already present.

<label for="example">Example field</label>
<input type="text" id="example" class="js-inputLengthWarning" maxlength="4" aria-describedby="guid-xxxx" />
<span id="guid-xxxx" class="inputLength inputLength--ok">
  <span class="inputLength__label">4</span> characters allowed
</span>

Accessibility

This component bakes in the following features automatically:

  • The message is linked to the input using aria-describedby so it is announced when the field receives focus.
  • The message uses a live region to communicate the number of remaining characters when the user pauses or finishes typing.

Additional options

There are a handful of classes and options that can be customised to suit your implementation.

OptionType.DefaultDescription
baseClassstringinputLengthClass applied to the main message container, appended immediately after the target input
labelClassstringinputLength__labelClass applied to the span element which wraps the integer count
okClassstringinputLength--okClass applied when the input length is < warnThreshold
warnClassstringinputLength--warnClass applied when the input length is > warnThreshold and < maxlength
stopClassstringinputLength--stopClass applied when the input length equals maxlength
warnThresholdint70Percentage of maxlength where the warnClass should be applied

Pass options through the constructor, for example:

inputLength.init({
  targetSelector: '.js-inputLengthWarning',
  labelClass: 'label',
  okClass: 'label--success',
  warnClass: 'label--warning',
  stopClass: 'label--danger',
  warnThreshold: 90
});