Created
March 26, 2017 09:30
-
-
Save devsnek/fd01f3d9d11ca0f7e0cabfb19acb179a to your computer and use it in GitHub Desktop.
a better typer.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function eek(element) { | |
const span = document.createElement('SPAN'); | |
element.appendChild(span); | |
return span; | |
} | |
class Typer { | |
constructor(element, words = [], options = {}) { | |
this.element = eek(element); | |
this.words = words; | |
this.options = { | |
delay: options.delay || 150, | |
endDelay: options.endDelay || 800, | |
}; | |
this.state = { | |
word: 0, | |
building: true, | |
}; | |
this.cursor = new Cursor(element); | |
this.interval = null; | |
this.doTyping(); | |
} | |
start() { | |
this.doTyping(); | |
} | |
stop() { | |
clearTimeout(this.timeout); | |
} | |
doTyping() { | |
this.cursor.stop(); | |
this.cursor.start(); | |
if (this.state.building) { | |
this.current += this.words[this.state.word][this.current.length]; | |
if (this.words[this.state.word].length <= this.current.length) { | |
this.state.building = false; | |
this.timeout = setTimeout(this.doTyping.bind(this), this.options.endDelay); | |
return; | |
} | |
} else { | |
this.current = this.current.slice(0, -1); | |
if (this.current.length <= 0) { | |
this.state.building = true; | |
if (this.state.word + 1 >= this.words.length) this.state.word = 0; | |
else this.state.word++; | |
} | |
} | |
this.timeout = setTimeout(this.doTyping.bind(this), this.options.delay); | |
} | |
set current(x) { | |
return this.element.innerHTML = x; | |
} | |
get current() { | |
return this.element.innerHTML; | |
} | |
} | |
class Cursor { | |
constructor(element) { | |
this.element = eek(element); | |
this.cursorDisplay = "▋"; | |
this.element.innerHTML = this.cursorDisplay; | |
this.element.style.transition = "all 0.1s"; | |
this.on = true; | |
this.timeout = null; | |
this.start(); | |
} | |
stop() { | |
clearInterval(this.interval); | |
} | |
start() { | |
this.interval = setInterval(this.update.bind(this), 400); | |
} | |
update() { | |
this.element.style.opacity = (+(this.on = !this.on)).toString(); | |
} | |
} | |
const x = new Typer(document.querySelector('#typer'), [ | |
'hi i am gus', | |
'bye', | |
'meme', | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment