Skip to content

Instantly share code, notes, and snippets.

@eneko89
Last active March 30, 2016 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneko89/5dafd7554a06226aa679 to your computer and use it in GitHub Desktop.
Save eneko89/5dafd7554a06226aa679 to your computer and use it in GitHub Desktop.
Rewrite 'el' element periodically with a string composed by an always static 'base' string and slices of 'sentence' in order to create a console prompt writing effect.
/**
* Check the following example in jsfiddle.
*
* <https://jsfiddle.net/qg9k3pmo/1/>
*/
/**
* Rewrite 'el' element periodically with a string composed by an
* always static 'base' string and slices of 'sentence' in order
* to create a console prompt writing effect. For example, if:
*
* el.innerHTML = 'Hi! I\'m Eneko!
* base = 'Hi!';
* sentence = ' How\'s goin\'?';
*
* With a period of a few millisecs, it'll write (el.innerHTML):
*
* 'Hi! I\'m Eneko'
* 'Hi! I\'m Enek'
* 'Hi! I\'m Ene'
* 'Hi! I\'m En'
*
* And so forth, until it reaches 'base' string. Then, it will do
* it forwards, writing the string provided in 'sentence'.
*
* @param {Element} el HTML DOM Element
*
* @param {String} base Base string that does not change.
*
* @param {String} sentence Sentence that will be rewritten.
*
* @param {Function} onEnd Called when the animation ends.
*/
function rewrite(el, base, sentence, onEnd) {
var oldSentence = el.innerHTML,
newSentence = base + sentence,
clk = setTimeout(del, DELETE_DELAY),
i = oldSentence.length;
// Constant write & delete delays.
var DELETE_DELAY = 60,
WRITE_DELAY = 65,
BLANK_WRITE_DELAY = 90;
/**
* Deletes content in h1 periodically until it reaches 'base'.
*/
function del() {
i--;
if (base.length <= i) {
el.innerHTML = oldSentence.substring(0, i);
clearTimeout(clk);
clk = setTimeout(del, DELETE_DELAY);
} else {
clearTimeout(clk);
clk = setTimeout(write, WRITE_DELAY);
}
}
/**
* Wirtes 'sentence' in h1 periodically and calls onEnd().
*/
function write() {
i++;
if (newSentence.length >= i) {
var delay;
// Write delays have a small random component. Also,
// before and after writing a blank space, delays are
// shightly longer. This makes the effect more natural.
if (newSentence.charAt(i-1) === ' '
|| newSentence.charAt(i) === ' ') {
delay = BLANK_WRITE_DELAY + (Math.random() * 20);
} else {
delay = WRITE_DELAY + (Math.random() * 20);
}
el.innerHTML = newSentence.substring(0, i);
clearTimeout(clk);
clk = setTimeout(write, delay);
} else {
clearTimeout(clk);
if (onEnd) {
onEnd();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment