Skip to content

Instantly share code, notes, and snippets.

@dblodorn
Created March 19, 2018 18:20
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 dblodorn/767b68753349b460c8ca2a61dca739db to your computer and use it in GitHub Desktop.
Save dblodorn/767b68753349b460c8ca2a61dca739db to your computer and use it in GitHub Desktop.
const typeWriter = (el, cb) => {
const TxtType = function(config) {
this.type = config.type
this.el = config.el
this.speed = config.speed
this.txt = ''
this.i = 0
this.tick()
}
TxtType.prototype.tick = function() {
const fullTxt = this.type
const charCount = fullTxt.length
const that = this
let delta = this.speed - Math.random() * 200
this.txt = fullTxt.substring(0, this.txt.length + 1)
this.el.innerHTML = `<span>${this.txt}</span>`
setTimeout(function() {
if ( that.i < charCount ) {
that.i ++
that.tick()
} else {
cb()
}
}, delta)
}
// Initialze
const type = el.getAttribute('data-type')
const speed = el.getAttribute('data-speed')
el.innerHTML = `<span></span>`
if (type) {
new TxtType({
el: el,
type: type,
speed: speed
})
}
}
export default typeWriter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment