<!-- BEGIN Google Font (just for fun) -->
<link href='http://fonts.googleapis.com/css?family=Capriola' rel='stylesheet'
type='text/css'>
<!-- END Google Font -->
<div id="container">
<h1>jQuery Word Count Plugin Demo</h1>
<textarea name="word_count" id="word_count" cols="30" rows="6"></textarea>
<ul id="counts">
<li>Total word Count : <span id="display_count_words">0</span>
</li>
<li>Total sentence Count : <span id="display_count_sentences">0</span>
</li>
<li>Average words per sentence Count : <span id="avg_words_per_sentence">0</span>
</li>
</ul>
<!-- BEGIN Attribution - You may delete this -->
<!-- You may freely use the code in this fiddle free of charge with no
attribution. This is just for me for looks. ;) -->
<div id="attribution"> <a href="http://www.clearthenoise.com/2012/08/jquery-word-count-plugin-demo-example.html"
target="_blank" title="jQuery Word Count Plugin - Article"><img src="https://dl.dropbox.com/u/13242521/cdn/clearthenoise/images/clear-the-noise-icon.png"/></a>
</div>
<!-- END Attribution -->
</div>
$.fn.wordCount = function (params) {
var words = {
counterWords: "display_count_words"
};
var sentences = {
counterSentences: "display_count_sentences"
};
var avgWordsPerSentence = {
counterAvgWordsPerSentence: "avg_words_per_sentence"
};
var total_words;
var total_sentences;
var avg_words_per_sentence;
if (params) {
$.extend(p, params);
}
//for each keyup function on text areas
this.keyup(function () {
// calculate the number of words
total_words = this.value.trim().split(/ +/).length;
jQuery('#' + words.counterWords).html(total_words);
// calculate the number of sentences
total_sentences = this.value.trim().split(/[\.\?\!]\s/).length;
jQuery('#' + sentences.counterSentences).html(total_sentences);
// calculate the average number of sentences
avg_words_per_sentence = total_words / total_sentences;
jQuery('#' + avgWordsPerSentence.counterAvgWordsPerSentence).html(avg_words_per_sentence);
});
};
$(document).ready(function () {
$('#word_count').wordCount();
//alternatively you can use the below method to display count in element with id word_counter
//$('#word_count').wordCount({counterElement:"word_counter"});
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.