Class CharacterCount

Character count component

Tracks the number of characters or words in the .govuk-js-character-count <textarea> inside the element. Displays a message with the remaining number of characters/words available, or the number of characters/words in excess.

You can configure the message to only appear after a certain percentage of the available characters/words has been entered.

Hierarchy (view full)

Constructors

Properties

_$root: HTMLElement
$screenReaderCountMessage: HTMLDivElement
$textarea: HTMLInputElement | HTMLTextAreaElement
$visibleCountMessage: HTMLDivElement
i18n: I18n
lastInputTimestamp: number = null
lastInputValue: string = ''
maxLength: number
valueChecker: number = null
defaults: CharacterCountConfig = ...

Character count default config

elementType: (new () => Element) = HTMLElement
moduleName: string = 'govuk-character-count'

Name for the component used when initialising using data-module attributes.

schema: Readonly<{
    anyOf: {
        errorMessage: string;
        required: string[];
    }[];
    properties: {
        i18n: {
            type: "object";
        };
        maxlength: {
            type: "number";
        };
        maxwords: {
            type: "number";
        };
        threshold: {
            type: "number";
        };
    };
}> = ...

Character count config schema

Accessors

Methods

  • Private

    Count the number of characters (or words, if config.maxwords is set) in the given text

    Parameters

    • text: string

      The text to count the characters of

    Returns number

    the number of characters (or words) in the text

  • Private

    Formats the message shown to users according to what's counted and how many remain

    Parameters

    • remainingNumber: number

      The number of words/characaters remaining

    • countType: string

      "words" or "characters"

    Returns string

    Status message

  • Private

    Handle focus event

    Speech recognition software such as Dragon NaturallySpeaking will modify the fields by directly changing its value. These changes don't trigger events in JavaScript, so we need to poll to handle when and if they occur.

    Once the keyup event hasn't been detected for at least 1000 ms (1s), check if the textarea value has changed and update the count message if it has.

    This is so that the update triggered by the manual comparison doesn't conflict with debounced KeyboardEvent updates.

    Returns void

  • Private

    Check if count is over threshold

    Checks whether the value is over the configured threshold for the input. If there is no configured threshold, it is set to 0 and this function will always return true.

    Returns boolean

    true if the current count is over the config.threshold (or no threshold is set)