Countable.js

Countable is a JavaScript function to add live paragraph-, word- and character-counting to an HTML element. Countable is a zero-dependency library and comes in at 1KB when minified and gzipped.

Demo

Installation

The preferred method of installation is bower.

bower install Countable

Alternatively, you can download the latest zipball or copy the script directly.


Usage

Countable offers easy-to-use methods you can use in your project. Countable.live() and Countable.once() accept one or more HTML elements and a callback that receives one parameter — holding all counted values — and this bound to the relevant element.


Available methods

To enable full live-counting on an element, call Countable.live().

var area = document.getElementById('area')



Countable.live(area, function (counter) {

  console.log(counter)

})

In order to remove the Countable functionality from an element, call Countable.die().

Countable.die(area)

There might be situations where you only want to count paragraphs, words and characters of an element once, i.e. if you want to display the word count of an article on your blog. In order to achieve this, call Countable.once().

Countable.once(area, function (counter) {

  console.log(counter)

})

Countable also provides a handy method to check if live-counting functionality is enabled on an element: Countable.enabled().

Countable.enabled(area)

Options

Countable.live() and Countable.once() both accept a third argument, an options object that allows you to change how Countable treats certain aspects of your element's text.

{

  hardReturns: false,

  stripTags: false

}

By default, paragraphs are split by a single return (a soft return). By setting hardReturns to true, Countable splits paragraphs after two returns.

Depending on your application and audience, you might need to strip HTML tags from the text before counting it. You can do this by setting stripTags to true.