I am trying to make a typewriter effect in javascript using array. At first I hardcoded a string in the array and the effect worked properly. Later, i tried doing the same thing with user input but it would not work.
This is the hardcoded version:
<html>
<head>
<script type="text/javascript">
var arr=new Array()
var start=0;
var end=start + 1;
arr[0]="Hello";
function write()
{
setTimeout(function() {
document.body.innerHTML=document.body.innerHTML + arr[0].slice(start,end);
start++;
end=start + 1;
if (start < 5) {
write();
}
}, 500);
}
onload=write();
</script>
</head>
<body>
</body>
</html>
This is the version in which I'm trying to get user input:
<html>
<head>
<script type="text/javascript">
var arr=new Array()
var start=0;
var end=start + 1;
arr[0]=document.getElementById('word').innerHTML;
function write()
{
setTimeout(function() {
document.body.innerHTML=document.body.innerHTML + arr[0].slice(start,end);
start++;
end=start + 1;
if (start < 5) {
write();
}
}, 500);
}
</script>
</head>
<body>
<input type="text" value="Hello World" id="word">
<br>
<a href="javascript:write()">Click</a>
</body>
</html>
Please tell me what changes i should make in my coding so that the version with user input works properly.
Use the
value
property instead ofinnerHTML
:And put that inside the
write
function, so that you get the value when the link is clicked instead of before the element even exists.In short: Usually - To get the current value of input (including select, textarea, radio, etc.) get it from attribute value, innerHTML from others.
No need to use an array :) You can write a lot less with the same effect.