var textarea = document.getElementById("textarea"),
statusBar = document.getElementById("status-bar");
function updateStatusBar() {
var text = textarea.value,
chars = text.length,
words = text.split(/\b\S+\b/g).length - 1,
lines = text.split("\n").length;
statusBar.value = lines + " lines, " + words + " words, " + chars + " characters";
}
-
\$\begingroup\$ Well, looks good :) But it is better to add at least a few words on what you want to expect us to do... \$\endgroup\$ – Alex Netkachov Nov 2 '13 at 6:24
-
\$\begingroup\$ possible duplicate of Review of status bar code \$\endgroup\$ – Alex Netkachov Nov 2 '13 at 6:25
I will give it a try:
These days I would recommend using document.querySelector, to write generic code which is well amenable to code re-factoring without introducing bugs.
So either:
var textarea = document.querySelector("#my-textarea") ,statusBar = document.querySelector("#status-bar");
or in later JavaScript versions, I believe >=1.6 (i.e. OK Server-side, when a specific JS-runtime can be guaranteed):
var [eltxtarea, elstatusbar] = document.querySelectorAll("#my-textarea,#status-bar");
Do not assign elements to Id's that are also keywords/attributes in the HTML specification (as such not textarea but e.g. my-textarea )
Bind the invocation of your function to an event or directly to underlying data-changes(requiring additional frameworks such as backbone.js). Do not use the respective exposed handler attribute but rather the attachEventHandler.
elstatusbar.attachEventHandler( "change", changeHandlerStatusbarUpdate);
The Handler:
var changeHandlerStatusbarUpdate = function(evt){
if(evt instanceof Event && evt.target instanceof HTMLTextAreaElement){
//you can be more specific. Event is just the Baseclass.
//for instance you may test for "KeyboardEvent" only
//the following logic should be improved: See threads of how to count words in a language/culture-specific fashion
var text = textarea.value,
chars = text.length,
words = text.split(/\b\S+\b/g).length - 1,
lines = text.split("\n").length,
stat = lines + " lines, " + words + " words, " + chars + " characters";
evt.target.value = stat;
}
}
- Do not put the updateStatusBar function in the global or window scope when the function relies upon textarea in the outside-scope, but use scope-encapsulation via closures (example), or a retrieve the target element within the function or through the event-target in a handler-function.
As pointed out in the source-comment, the word-counting is much to trivial and not "culture-invariant" as is the case right now.