Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div id="display"></div>
  <div id="count">Type in here!</div>
</body>
</html>
 
/* what am I creating? A word counter.
 * How do I want to use it?
 * -Call a function, passing in an element and a callback function
 * -Bind the word counter to that element
 * -When the word count changes, pass the new count to the callback function
 */
window.onload = function() {
  var countDiv = document.getElementById('count');
  wordCounter.bind(countDiv, displayCount);
  //you can pass in whatever function you want. I made one called displayCount, for example
};
var wordCounter = {
  current : 0,
  bind : function(elem, callback) {
    this.ensureEditable(elem);
    this.handleIfChanged(elem, callback);
    
    var that = this;
    elem.addEventListener('keyup', function(e) {
      that.handleIfChanged(elem, callback);
    });
  },
  handleIfChanged : function(elem, callback) {
    var count = this.countWords(elem);
    if (count !== this.current) {
      this.current = count;
      callback(count);
    }
  },
  countWords : function(elem) {
    var text = elem.textContent;
    var words = text.match(/(\w+\b)/g);
    return (words) ? words.length : 0;
  },
  ensureEditable : function(elem) {
    if (
      elem.getAttribute('contenteditable') !== 'true' && 
      elem.nodeName !== 'TEXTAREA' &&
      elem.nodeName !== 'INPUT'
    ) {
      elem.setAttribute('contenteditable', true); 
    }
  }
};
var display = document.getElementById('display');
function displayCount(count) {
  //this function is called every time the word count changes
  //do whatever you want...the word counter doesn't care.
  display.textContent = 'Word count is: '+count;
}
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers