Add live paragraph-, word- and character-counting to an HTML element.

Overview

Countable

Build Status Code Climate Latest Tag License

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.

View the Demo

Installation

The preferred method of installation is npm or yarn.

npm i --save-dev countable
yarn add --dev countable

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

Usage

Countable is available as a Node / CommonJS module, an AMD module and as a global. All methods are accessed on the Countable object directly.

Callbacks

The on and count methods both accept a callback. The given callback is then called whenever needed with a single parameter that carries all the relevant data. this is bound to the current element. Take the following code for an example.

Countable.count(document.getElementById('text'), counter => console.log(this, counter))
=> <textarea id="text"></textarea>, { all: 0, characters: 0, paragraphs: 0, words: 0 }
Property Meaning
paragraphs The number of paragraphs. Paragraphs can be separated by either a soft or a hard (two line breaks) return. To use hard returns, set the corresponding option (hardReturns).
sentences The number of sentences. Sentences are separated by a sentence-terminating character.
words The number of words. Words are split using spaces.
characters The number of characters (without spaces). This contains all non-whitespace characters.
all The number of characters including whitespace. This is the total number of all characters in the element.

Countable.on(elements, callback, options)

Bind the callback to all given elements. The callback gets called every time the element's value or text is changed.

Countable.on(area, counter => console.log(counter))

Countable.off(elements)

Remove the bound callback from all given elements.

Countable.off(area)

Countable.count(elements, callback, options)

Similar to Countable.on(), but the callback is only executed once, there are no events bound.

Countable.count(area, counter => console.log(counter))

Countable.enabled(elements)

Checks the live-counting functionality is bound to the given.

Countable.enabled(area)

Options

Countable.on() and Countable.count() 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,
  ignore: []
}

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.

Sometimes it is desirable to ignore certain characters. These can be included in an array and passed using the ignore option.

Browser Support

Countable supports all modern browsers. Full ES5 support is expected, as are some ES6 features, namely let and const.

Comments
  • Demo Site Renders Wrong in IE10

    Demo Site Renders Wrong in IE10

    At least on Windows 7. The gradient for the download button is broken: button

    Also, the counters show stats for the prompt text, when that doesn't happen in Firefox: count

    opened by epmatsw 11
  • Remove punctuation before counting words

    Remove punctuation before counting words

    Hi, great script!

    It would be great if text like "Bonjour !" wasn't counted as two words. You would have to pass the string through a regExp that removed common punctuation characters before splitting into words.

    Also, line 66 can be rewritten without the .split i.e. from this:

    characters: str ? str.replace(/\s/g, '').split('').length : 0

    to this:

    characters: str ? str.replace(/\s/g, '').length : 0

    Again, great script - apologies for me being pedantic about details like this!

    opened by freqdec 9
  • Issue with Knockout value driven area

    Issue with Knockout value driven area

    I was using once before every time an update happened which was fine, but I thought it would probably be easier to use live, but it doesnt update.

    The element its targeting is driven by a knockout observable like so:

    <div id="preview" data-bind="text: someTextObservable"></div>

    So that div will change its content every time someTextObservable changes, now I notice in the source code that it is looking for key pressed based events, whereas in this case those would not apply as its a div not an input.

    I know there are some events for mutations part of the newer html spec so not sure if you are fussed about supporting them or not, I can go back to just using once whenever it updates which is fine, but just wanted to raise this incase you wanted to extend support.

    opened by grofit 4
  • li element with value 0 causes original.replace() exception

    li element with value 0 causes original.replace() exception

    When using countable on an li element with a value, the following error occurs (in Chrome):

    Uncaught TypeError: original.replace is not a function
    

    Tracing this back it's because the li element value is a number, and obviously the replace function belongs to the string prototype. Adding:

       if(typeof(original) !== 'string'){
            original = "";
       }
    

    around line 177 is a kludgy fix... but not great.

    opened by paul-muckypuddle 4
  • Feature request: ignore invisible space characters

    Feature request: ignore invisible space characters

    This is a feature request to ignore zero width space characters (http://www.fileformat.info/info/unicode/char/200b/index.htm) in the character and word count.

    HTML text editors such as Redactor (http://imperavi.com/redactor/) sometimes insert zero width space characters.

    I also would like to contribute by sending send a pull request but would like to discuss the functionality first.

    opened by jurreantonisse 4
  • Countable doesn't count newlines

    Countable doesn't count newlines

    ~~Countable does not seem to recognise newline characters (line feed / carriage return). If this is intentional,~~ I would like to suggest a new option to optionally enable counting newline characters as well (which are currently omitted in https://github.com/RadLikeWhoa/Countable/blob/master/Countable.js#L190).

    Related: https://github.com/TryGhost/Ghost/issues/1432

    I'm happy to provide a PR.

    opened by halfdan 3
  • Fixed RegEx & Added ucs2decode

    Fixed RegEx & Added ucs2decode

    I needed to get my mind off of work so I went ahead and fixed the 3 open issues. You can check it out at http://jsfiddle.net/j6nkw/3/

    I think this could do with a minified version.

    Specific Changes / issues

    1. The word counter wasn't greedy enough so it would match " but not "x"
    2. Excluding HTML tags required a new RegularExpression. Made it selectable by looking for an omit attribute if it is "on" then html tags aren't counted.
    3. Since punycode and Countable are both MIT licensed took the ucs2decode function and used to correct counting for Unicode characters.
    opened by craniumslows 3
  • Count symbols/code points more accurately

    Count symbols/code points more accurately

    See http://pastebin.com/raw.php?i=bZ7dbreC for some example characters that get miscounted. (GitHub won’t let me post them here.)

    Perhaps this can help: http://mathiasbynens.be/notes/javascript-encoding It explains the problem in more detail and also offers a solution. You could use Punycode.js to make it really easy.

    opened by mathiasbynens 3
  • 3.0.1 on npm

    3.0.1 on npm

    Could you please publish 3.0.1 on npm ?

    npm info countable
    
    { name: 'countable',
      description: 'Countable is a JavaScript library to add live paragraph-, word- and character-counting to an HTML element.',
      'dist-tags': { latest: '3.0.0' },
      versions: [ '2.0.2', '2.1.0', '2.1.1', '3.0.0' ]
    
    opened by vogloblinsky 2
  • Validate on HTMLCollection

    Validate on HTMLCollection

    The MDN docs and most browsers document functions such as getElementsByClassName and getElementsByTagName returning HTMLCollections rather than node lists. Unfortunately this doesn't pass the current validation which only checks for [object NodeList]. Something like:

      function _validateArguments (elements, callback) {
        var nodes = Object.prototype.toString.call(elements),
            validObject = nodes === '[object NodeList]' || nodes === '[object HTMLCollection]',
            elementsValid = elements && ((validObject && elements.length) || (elements.nodeType === 1)),
            callbackValid = callback && typeof callback === 'function'
    
        if ('console' in window && 'warn' in console) {
          if (!elementsValid) console.warn('Countable: No valid elements were found')
          if (!callbackValid) console.warn('Countable: "' + callback + '" is not a valid callback function')
        }
    
        return elementsValid && callbackValid
      }
    

    But I'm not sure how the tests would work since they seem to be designed for single elements.

    opened by Mrjaco12 2
  • Parse whitespace html entities as spaces and treat standard blockLike…

    Parse whitespace html entities as spaces and treat standard blockLike…

    … HTML elements as word separators when stripTags option set.

    Fixes https://github.com/RadLikeWhoa/Countable/issues/38 by replacing the html entities with their unicode equivalent.

    Also parses html block elements as word separators, e.g., <div>one</div><div>two</div> counts as two words, <span>one</span><span>two</span> still counts as just one word.

    opened by rawrmonstar 2
  • ignoreReturns: true not respected

    ignoreReturns: true not respected

    The default implementation of below does not respect the ignoreReturns: true:

    $( window ).on('load', function() {
        Countable.on( 
            document.getElementById('my_area'), 
            counter => console.log(counter),
            {
                ignoreReturns: true
            }
        )  
    });
    

    Doing so, the all property still counts returns (enter/newline)

    Thus, we always get a wrong character count when doing this:

    $( window ).on('load', function() {
        Countable.on( 
            document.getElementById('my_area'), 
            counter => document.getElementById('my_result').innerHTML = counter.all.toString(),
            {
                ignoreReturns: true
            }
        )  
    });
    

    The doc clearly states that we shall use that option to Ignore returns when calculating the all property.

    Suggestions?

    opened by smileBeda 0
  • WYSIWYG Summernote issue

    WYSIWYG Summernote issue

    Hi first of all good job on this plugin, the thing is for me, is not working if I have on the same text-area a char counter and your plugin implemented, and the first logic for character counting is not working, no error is thrown Is there any solution for this?

    opened by unixdevel 0
  • Doesn't minify with webpack in a create-react-app project

    Doesn't minify with webpack in a create-react-app project

    When trying to build an app using Countable, the build fails, seemingly because there is no es5 version of the library. Can an es5 file be auto-compiled into the dist?

    opened by shivavelingker 0
  • V3.0.1  - Error with Array.isArray at line 197 for jquery elements

    V3.0.1 - Error with Array.isArray at line 197 for jquery elements

    An array of jquery elements does not result in "true" for "Array.isArray(elements)". Recommend putting this back to checking elements.length.

    opened by WaylonOKC 0
Releases(3.0.1)
  • 3.0.1(Jun 11, 2018)

    • Added support for string parameter to Countable#count. You can now pass a single string instead of an element or a list of elements as the first parameter, e.g. Countable.count('hello world', callback).
    • Improve documentation.
    Source code(tar.gz)
    Source code(zip)
  • v3.0.0(Jul 13, 2017)

    • Countable::on and Countable::off replace Countable::live and Countable::die. The new methods work exactly the same, apart from the name change.

    • Countable::once has been removed. The method is now available exclusively as Countable::count.

    • Countable::enabled now accepts either single elements or lists of elements. When a list is passed, the validation checks if all elements have the Countable functionality.

    • Options have been simplified. Support for ignoreReturns and ignoreZeroWidthSpace has been removed in favour of a more general ignore option, which is an array of characters that should be ignored.

    • Added a minified version.

    • Removed legacy support. Countable now uses things like let and const and expects ES5 methods to be present. This mainly drops support for IE before version 11.

    • Reduced file size by almost 25%.

    Source code(tar.gz)
    Source code(zip)
  • v2.1.1(May 1, 2015)

    • Fixes a bug where IE9 would not react to DELETE, BACKSPACE and CUT commands.
    • Fixes a bug where Countable could not be concatenated with other files.
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Nov 6, 2014)

    • Sentence counting has been added. The number of sentences (sentences) can be accessed as part of the counter object.
    • Countable.once is now aliased as Countable.count
    • Zero-width characters are now ignored by default. This can be changed using the ignoreZeroWidth option.
    Source code(tar.gz)
    Source code(zip)
  • v2.0.2(Aug 14, 2014)

  • v2.0.1(Aug 14, 2014)

  • v2.0.0(Aug 14, 2014)

    • Countable has a new Syntax. You can now use Countable.live, Countable.once, Countable.die and Countable.enabled. Notes on upgrading is provided in the README.
    • Countable can now work on multiple elements with one function call.
    • Prevent a XSS bug. (Thanks to Rob--W)
    Source code(tar.gz)
    Source code(zip)
  • v1.4.2(Aug 14, 2014)

  • v1.4.1(Aug 14, 2014)

  • v1.4.0(Aug 14, 2014)

  • v1.3.0(Aug 14, 2014)

  • v1.2.0(Aug 14, 2014)

  • v1.1.1(Aug 14, 2014)

  • v1.1.0(Aug 14, 2014)

    • Include number of characters including whitespace.
    • Countable is now available on Bower.
    • Improve performance when counting the values.
    • Improve performance when trimming strings by using String::trim when available.
    • Better documentation.
    Source code(tar.gz)
    Source code(zip)
Owner
Sacha Schmid
Developer and designer.
Sacha Schmid
Simple-load-more - This jQuery function will add a functionality to load 5 (or custom) more items. No AJAX functionality.

Simple Load More This jQuery plugin will add a functionality to load 5 (or custom) more items. Best for lists that are long and you want to hide all e

Zeshan Ahmed 28 Jan 4, 2023
Automatically persist your forms' text and select field values locally, until the form is submitted.

Garlic.js Garlic.js allows you to automatically persist your forms' text and select field values locally, until the form is submitted. This way, your

Guillaume Potier 2.4k Dec 21, 2022
typeahead.js is a fast and fully-featured autocomplete library

typeahead.js Inspired by twitter.com's autocomplete search functionality, typeahead.js is a flexible JavaScript library that provides a strong foundat

Twitter 16.5k Jan 4, 2023
jQuery plugin for styling checkboxes and radio-buttons

English description | Описание на русском jQuery-plugin for styling checkboxes and radio-buttons. With skin support. Version: 2.0.0 Project page and d

Denis Ineshin 70 Sep 24, 2022
A set of flat and 3D progress button styles where the button itself serves as a progress indicator

A set of flat and 3D progress button styles where the button itself serves as a progress indicator. 3D styles are used for showing the progress indication on one side of the button while rotating the button in perspective.

Codrops 608 Oct 19, 2022
Simple Word Counting

Simple Word Counting Clone this repository ✅ git clone https://github.com/Mindula-Dilthushan/simple-word-counting.git License ?? MIT License © Mindula

Mindula Dilthushan Manamperi 12 Jul 14, 2022
null 3.9k Dec 30, 2022
Dynamic (Per line/paragraph depend on language you type) RTL/LTR support plugin for Obsidian.md

In the name of Allah Obsidian Dynamic RTL Dynamic (Per line/paragraph depending on the language you type) RTL/LTR support plugin for Obsidian.md Previ

Amirreza Aliakbari 33 Jan 2, 2023
Lets you add a character to Hacker News links to add social media and OpenGraph previews for sharing on things like Slack or Twitter.

news.ycombinator1.com Lets you add a character to Hacker News links to add social media and OpenGraph previews for sharing on things like Slack or Dis

Ian Langworth ☠ 38 Sep 18, 2022
Wordle and Termooo style classic word guessing game for the command line. One new word per day!

Wordle and Termooo style classic word guessing game for the command line. One new word per day!

Anderson Silva 3 Nov 27, 2022
Remade from Catch-Word-js [https://github.com/Jortsoft/Catch-Word-js]

Author: https://github.com/Jortsoft Catch-Word-js This is very simple game catch word with JavaScript and Jquery install and run guide! download proje

Dimitri Kvachakhia 3 Jun 12, 2021
This bot was created with the sole purpose of replying to messages with the word "que" with the word "so"

UselessComplete This bot was created with the sole purpose of replying to messages with the word "que" with the word "so" If you want tu support the b

ThisIsAName 6 Aug 30, 2022
基于vue3.0-ts-Element集成的简洁/实用后台模板!《带预览地址》vue-admin;vue+admin;vue-element;vue+element;vue后台管理;vue3.0-admin;vue3.0-element。

一、基于vue3.0+ts+Element通用后台admin模板 二、在线预览地址:http://admin.yknba.cn/ 三、下载使用: 1、克隆代码 通过git将代码克隆到本地;或者使用下载安装包模式进行下载。 2、进入目录 进入项目的根目录:vue3.0-ts-admin 3、安装依

null 64 Dec 16, 2022
Website to display chats and gifts in realtime from your TikTok LIVE stream. Demo project for TikTok-Live-Connector library.

TikTok-Chat-Reader A chat reader for TikTok LIVE utilizing TikTok-Live-Connector and Socket.IO to forward the data to the client. This demo project us

David 104 Dec 31, 2022
Node.js library to receive live stream chat events like comments and gifts in realtime from TikTok LIVE.

TikTok-Live-Connector A Node.js library to receive live stream events such as comments and gifts in realtime from TikTok LIVE by connecting to TikTok'

David 399 Jan 4, 2023
JavaScript micro-library: pass in an element and a callback and this will trigger when you click anywhere other than the element

Add a click listener to fire a callback for everywhere on the window except your chosen element. Installation run npm install @lukeboyle/when-clicked-

Boyleing Point 5 May 13, 2021
jQuery plugin to export a html table to JSON, XML, CSV, TSV, TXT, SQL, Word, Excel, PNG and PDF

tableExport.jquery.plugin Export HTML Table to CSV DOC JSON PDF PNG SQL TSV TXT XLS (Excel 2000 HTML format) XLSX (Excel 2007 Office Open XML format)

null 918 Dec 29, 2022
A jquery plugin that allows an html page to be converted and/or downloaded into a Microsoft Word Document with an emphasis on performance

googoose A jquery plugin that allows an html page to be converted and/or downloaded into a Microsoft Word Document with an emphasis on performance Abo

Aaron Adel 32 Jan 3, 2023
An open, collaborative and evolving character creator project for the open metaverse.

Avatar Creator An open, collaborative and evolving 3D avatar creator for the open metaverse. Want to contribute? Please check out the issues, or submi

Atlas Foundation 23 Dec 17, 2022