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.
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)
}
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();
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With