Question

I try to create a more realistic typewriting, which makes typing errors and corrects them by removing/adding chars.

Yet, I made a simple solution which can add and remove chars via slice. But I don't know how to implement the misstyping-feature.

Here's what I've done so far:

var str = 'Foo bar is not equal to bar foo.';
var len = str.length;

var elem = document.body;

var rem = len;
var add = 0;

(function type(){
  if(!rem || add === len) return;

  // write
  elem.innerHTML = str.slice(0, ++add);

  // remove
  // elem.innerHTML = str.slice(0, --rem);

  setTimeout(type, 100);
}());

http://jsbin.com/upufaf/6/edit

Any ideas or already finished solutions how to get this to work?

BTW: There's already something called realistic typewriter, however I think this solution is a bit too bloated for that simple problem.

Was it helpful?

Solution

var str = 'Foo bar is not equal to bar foo.' ;
var alphabet = 'abcdefghijklmnopqrstuvwxyz' ;
var pos = 0 ;
var tmpStr = '' ;
var doBackspace = false ;
function startTyping (str) {

    if(doBackspace) {
        tmpStr = tmpStr.slice(0,tmpStr.length-1);
        doBackspace = false ;
    } else {

        if(Math.ceil((Math.random()*100)) < 80) {
            tmpStr += str[pos] ;
            pos++ ;

        } else {
            tmpStr += alphabet[Math.floor(Math.random()*(alphabet.length))] ;
            doBackspace = true ;
        }
    }   
    $('body').html(tmpStr) ;

    if(pos < str.length) {
        setTimeout(function(){
            startTyping(str)
        }, 300) ;
    }
}
$(document).ready(function(){
    startTyping(str) ;
});

Can change interval 300 to higher value to reduce typing speed, also add characters to alphabet to increase number of possible mistaken chars, 80 to lower value to increase chance for a mistake

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top