Reputation: 450
So I currently have some javascript code that creates a "typing" effect. During the typing, there is a caret at the end that mimics the caret type when typing into a console. When the typing has finished, I'd like for the caret to begin blinking, just as it would within a console. Here is the code used for it:
html:
<div id="typedtext"></div>
javascript:
// set up text to print, each item in array is new line
var arrText = new Array(
"This is an example of some,",
"typed text."
);
var speed = 60; // time delay of print out
var index = 0; // start printing array at this posision
var arrLength = arrText[0].length; // the length of the text array
var scrollAt = 20; // start scrolling up at this many lines
var textPos = 0; // initialise text position
var contents = ''; // initialise contents variable
var row; // initialise current row
function typewriter()
{
contents = ' ';
row = Math.max(0, index-scrollAt);
var destination = document.getElementById("typedtext");
while ( row < index ) {
contents += arrText[row++] + '<br />';
}
destination.innerHTML = contents + arrText[index].substring(0, textPos) + "█";
if ( textPos++ == arrLength ) {
textPos = 0;
index++;
if ( index != arrText.length ) {
arrLength = arrText[index].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", speed);
}
}
typewriter();
Is this possible?
Upvotes: 1
Views: 617
Reputation: 532
You can add a few CSS scripts to add blinking effect to the caret. Move the █
inside a <span>
and add .blink
class to it.
// set up text to print, each item in array is new line
var arrText = new Array(
"This is an example of some,",
"typed text."
);
var speed = 60; // time delay of print out
var index = 0; // start printing array at this posision
var arrLength = arrText[0].length; // the length of the text array
var scrollAt = 20; // start scrolling up at this many lines
var textPos = 0; // initialise text position
var contents = ''; // initialise contents variable
var row; // initialise current row
function typewriter() {
contents = ' ';
row = Math.max(0, index - scrollAt);
var destination = document.getElementById("typedtext");
while (row < index) {
contents += arrText[row++] + '<br />';
}
destination.innerHTML = contents + arrText[index].substring(0, textPos) + "<span class='blink'>█<span>";
if (textPos++ == arrLength) {
textPos = 0;
index++;
if (index != arrText.length) {
arrLength = arrText[index].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", speed);
}
}
typewriter();
.blink {
animation: blink-animation 1s steps(5, start) infinite;
-webkit-animation: blink-animation 1s steps(5, start) infinite;
}
@keyframes blink-animation {
to {
visibility: hidden;
}
}
@-webkit-keyframes blink-animation {
to {
visibility: hidden;
}
}
<div id="typedtext"></div>
Upvotes: 2