jQuery Word, Sentence and Average Sentences Count Example Demo
jQuery Word, Sentence and Average Sentences Count Example Demo
HTML
<link href='http://fonts.googleapis.com/css?family=Capriola' rel='stylesheet'
type='text/css'>
<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>
<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>
</div>
CSS
#container {
width:500px;
padding: 15px;
background: #1b3e59;
font-family:'Capriola', Arial, sans-serif;
font-weight: 400;
/*using Google Web Font */
-webkit-box-sizing: border-box;
/* keep all the padding in the 600px width box */
-moz-box-sizing: border-box;
box-sizing: border-box;
overflow: auto;
}
#container h1 {
font-size: 26px;
padding: 10px;
color: #ccc;
text-shadow: 1px 1px 1px #132c40;
}
#word_count {
width: 100%;
-webkit-box-shadow: 0px 0px 4px 0px #ccc;
box-shadow: 0px 0px 4px 0px #ccc;
}
#counts {
color: #999;
padding: 10px;
}
#counts span {
color: #fff;
}
#attribution {
float: right;
}
#attribution a {
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
opacity: 0.5;
}
#attribution a:hover {
opacity: 1;
}
JavaScript
$.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();
});