words counter

//1. Add html element /* <textarea name="textCount" id="textCount"></textarea> <p>You have <span id="wordCount">0 words</span> and <span id="charCount">0 characters</span></p> */ //2. Add JQuery <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> //3. Script part var wordCounter = { init: function() { this.DOM(); this.events(); }, DOM: function() { this.textbox = $("#textCount"); this.wordCount = $("#wordCount"); this.charCount = $("#charCount"); }, events: function() { this.textbox.on("input", this.count.bind(this)); }, count: function() { var words = this.textbox.val().split(" "), chars = this.textbox.val(); //DELETE EMPTY STRINGS for (var i = 0; i < words.length; i++) { while (words[i] === "") { words.splice(i, 1); } } //COUNT WORDS if (words.length === 1) { this.wordCount.text(words.length + " word"); } else { this.wordCount.text(words.length + " words"); } //COUNT CHARACTERS if (chars.length < 0) { words = []; } else if (chars.length === 1) { this.charCount.text(chars.length + " character"); } else { this.charCount.text(chars.length + " characters"); } } } //4. Initialize the Word and Character Counter. wordCounter.init();

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.