JSFiddle - React, Tailwind, and code Playground
by BurpmanJunior
HTML
<div id="target">Something</div>
CSS
body{
background-color: #423b4f;
color: #fff;
font-family: monospace;
}
JavaScript
/**
* Type Transition
* @TODO: Fix inactive tab animation propagation on reactivation
*/
var typeTransition = function(writeElem, typeStrings, settings){
var self = this;
// Element
if(writeElem.nodeType){
self.ELEM = writeElem;
}else{
self.ELEM = document.querySelector(writeElem);
}
if(!self.ELEM){
return false;
}
// Strings
self.STRINGS = [self.ELEM.textContent].concat(typeStrings);
self.CURRENT = 0;
// Settings
self.CONF = {
duration: 600,
pause: 4000,
cursor: '|'
}
if(typeof settings === 'object'){
for(prop in settings){
self.CONF[prop] = settings[prop];
}
}
// Initiate next transition
self.PROCESS = function(){
self.nextString();
setTimeout(self.PROCESS, self.CONF.pause + self.CONF.duration);
}
// Run
setTimeout(self.PROCESS, self.CONF.pause);
}
/**
* Runs transition on current and calculated next strings
*/
typeTransition.prototype.nextString = function(){
var self = this,
next;
// Calculate next
next = (self.CURRENT + 1 >= self.STRINGS.length ? 0 : self.CURRENT + 1);
// Run transition
self.overwrite(self.STRINGS[self.CURRENT], self.STRINGS[next]);
// Update current
self.CURRENT = next;
}
/**
* Overwrites from string with to string with space buffer where needed
*/
typeTransition.prototype.overwrite = function(from, to){
var self = this,
stepSize,
currentString,
maxIteration,
i = 0;
// Set vars
maxIteration = Math.max(from.length, to.length);
stepSize = self.CONF.duration / maxIteration;
// Expand from into array
currentString = from.split('');
// Replace current iteration letter
var replaceLetter = function(){
// Splice space string if nothing can replace current iteration
currentString.splice(i, 1, (to[i] ? to[i] : '<span data-ttspace style="display: inline-block;"> </span>'));
// Splice cursor
currentString.splice(i + 1, 1, self.CONF.cursor);
//...