JSFiddle - React, Tailwind, and code Playground
by CommandLineDesign
HTML
<div id="myDiv"></div>
JavaScript
var TypingGame = function(elementId, text) {
var game = this;
this.container = document.getElementById(elementId);
this.text = text;
this.words = text.split(' ').length;
this.cursor = 0;
this.errors = 0;
//Configure Input
this.input = {};
//Keyup Event-Handler for typing action
this.input.check = function(element) {
//Define submit method
this.submitWord = function() {
if (this.value.trim() == game.text.split(' ')[game.cursor]) {
console.log('correct');
} else {
console.log('incorrect');
console.log(this.value + ' NEQ ' + game.text.split(' ')[game.cursor]);
game.errors++;
}
game.cursor++;
this.value = '';
}
//define end condition handler
this.endGame = function(){
game.endGame();
}
//Begin flow-control
if (game.cursor === 0) {
game.startTime = new Date().getTime();
}
if (element.keyCode == 32) { //spacebar - submit word
this.submitWord();
}
if (game.cursor == game.text.split(' ').length) {
game.endGame();
}
}
this.input.build = function() {
var field = document.createElement('input');
field.id = 'myId';
field.addEventListener('keydown', game.input.check);
return field;
}
this.input.render = function() {
var target = document.getElementById(elementId);
target.appendChild(game.input.build());
}
// Display Text to be typed
this.content = {};
this.content.build = function() {
var container = document.createElement('div');
container.id = 'myContentId';
var content = document.createTextNode(game.text);
container.appendChild(content);
return container;
}
this.content.render = function() {
game.container.appendChild(game.content.build());
}
//Finish the game, draw scoreboard
this.endGame = function() {
console.log('finished!');
game.endTime = new Date().getTime();
console.log((game.endTime - game.startTime) / 1000);
...