Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate the look of typing, not the actual keypresses, in javascript

I'm trying to write a simple function that will make it appear as though someone is typing in a textarea

-- This is my function (forgive me if its atrocious, but I don't normally use javascript) --- The console.log() part works fine, but for some reason I cannot get this script to update the dom the way I would expect...

        function type(string) {
            value = "";

            el = document.getElementById("typeArea");
            for (var i = 0; i < string.length; i++) {
                value += string[i];
                //$("#fbw > textarea").val(value);
                el.textContent = value;
                console.log(value);
                sleep(160);
            }
            sleep(2000);
        }

I appreciate any insight you can give me.

like image 356
rm-vanda Avatar asked May 15 '14 20:05

rm-vanda


2 Answers

jsFiddle Demo

All you were missing was a construct instead of Sleep. The js approach for accomplishing this is to use a timeout and a recursive call in order to iterate through your string

function type(string,element){
 (function writer(i){
  if(string.length <= i++){
    element.value = string;
    return;
  }
  element.value = string.substring(0,i);
  if( element.value[element.value.length-1] != " " )element.focus();
  var rand = Math.floor(Math.random() * (100)) + 140;
  setTimeout(function(){writer(i);},rand);
 })(0)
}
like image 182
Travis J Avatar answered Oct 29 '22 01:10

Travis J


You can do something like this using setTimeout function. Codepen

$(function(){
  simulateTyping('looks  like someone is typing...', '#txt')

  function simulateTyping(str, textAreaId) {
    var textArea = $(textAreaId);

    var currentCharIndex = 0;
    function typeChar(){
      if (currentCharIndex >= str.length)
        return;
      var char = str[currentCharIndex];
      textArea.val(textArea.val() + char);
      currentCharIndex ++;
      setTimeout(typeChar, 500);
    } 

    typeChar();

  }
})
like image 42
milagvoniduak Avatar answered Oct 29 '22 00:10

milagvoniduak