Reputation: 1413
I am trying to capture a sentence from a user's input and replicate it as a typing effect. I am using JavaScript to perform the task.
I am able to capture the input and display it with console.log()
, but when I add the typing effect function, it doesn't seem to work.
My code are as follow. What's going wrong?
var getInput = document.getElementById("input");
getInput.onkeyup = function(e) {
if (e.keyCode == 13) {
var i = 0;
var text = input.value;
function typing() {
if (i < text.length) {
document.getElementById('output').innerHTML += text.charAt(i);
i++;
setTimeout(typeWriter, 200);
}
}
e.currentTarget.value = "";
}
}
<link href="https://fonts.googleapis.com/css?family=Francois+One" rel="stylesheet">
<div class="background"></div>
<div class="input"></div>
<div class="typing">
<div class="input-group">
<div class="form-group">
<label for="text">Please Type Here:</label>
<input type="text" class="form-control" id="input">
</div>
</div>
</div>
<div class="output" id="output">
</div>
Upvotes: 0
Views: 588
Reputation: 5853
You can use the keyup
event in Javascript and listen to that event and update your DOM element on each keyboard stroke.
window.onload = function() {
let myInputElement = document.querySelector(`#myInput`);
if (myInputElement) {
myInputElement.addEventListener('keyup', function(event) {
let myTextElement = document.querySelector(`#myText`);
myTextElement.innerText = myInputElement.value;
});
}
}
<html>
<head>
</head>
<body>
<input id="myInput" />
<br>
<hr>
<p id="myText"></p>
</body>
Upvotes: 0
Reputation: 23859
You have defined the typing
function, but haven't called it.
Plus, in the setTimeout
, you've called typeWriter
function which is undefined
. You wanted calling typing
instead:
var getInput = document.getElementById("input");
getInput.onkeyup = function(e) {
if (e.keyCode == 13) {
var i = 0;
var text = input.value;
function typing() {
if (i < text.length) {
document.getElementById('output').innerHTML += text.charAt(i);
i++;
setTimeout(typing, 200);
}
}
typing();
e.currentTarget.value = "";
}
}
<div class="background"></div>
<div class="input"></div>
<div class="typing">
<div class="input-group">
<div class="form-group">
<label for="text">Please Type Here:</label>
<input type="text" class="form-control" id="input">
</div>
</div>
</div>
<div class="output" id="output">
</div>
Upvotes: 2