Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate user writing in a textbox javascript

I have this form and I write into it using:

document.getElementById("val").value ="value";

This inserts the value automatically into the textbox.

Is it possible to insert it simulating user writing? So inserting a letter one by one and not all together?

like image 223
Mariano De Luca Avatar asked Dec 22 '25 03:12

Mariano De Luca


1 Answers

An example that allows an onset delay, interresponse-time between keystrokes, preservation of cursor position, as well as native change event triggers:

let target = document.getElementById('testarea')
target.selectionStart = 30;
target.focus();

/**
 * simulateTextareaInput
 * @param id {string} The id of the textarea to target.
 * @param text {string} The text to input, character-by-character.
 * @param lat {number} The latency / time to wait before beginning input.
 * @param irt {number} The interresponse-time between each input / simulated keystroke.
 */
const sim = function (id, text, lat, irt) {
    const length = text.length-1;
    var current = 0;
    /**
     * insertText
     * @param str {string} The character to input into the text area
     */
    const insertChar = function(char) {
        // get element
        var target = document.getElementById(id);
        if (target !== null) { // if it is found in the dom ...
            let [start, end] = [target.selectionStart, target.selectionEnd];
            // insert char
            target.setRangeText(char, start, end, 'select');
            // move cursor forward 1
            target.selectionStart = start+1;
            // trigger any onChange listeners
            var event = new window.Event('change', { bubbles: true });
            target.dispatchEvent(event);
        } else {
            console.log(`No <textarea> with id "${id}" found.`)
        };
    };
    const write = function() {
        // insert current character
        insertChar(text[current]);
        if(current < length) { // so long as there are more chars to input
            current++; // increment
            setTimeout(function(){write()},irt); // recurisvely write next char
        };
    };
    setTimeout(function(){
        // kickoff input 
        setTimeout(function(){write()},irt)
    },lat); // wait this long before starting
};

sim('testarea','this text was simulated after 2s -- cool!',2000,50);
textarea {
  width: 500px;
  height: 100px;
}
<!-- begin demo -->

<textarea id='testarea'>
hello world
simulated output: 
new text will appear on the above line
</textarea>
like image 187
Harley Lang Avatar answered Dec 23 '25 17:12

Harley Lang