Skip to content

Instantly share code, notes, and snippets.

@nuel
Created August 5, 2022 21:46
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 nuel/85a44c3efdd90232ce0cccb4f44728d2 to your computer and use it in GitHub Desktop.
Save nuel/85a44c3efdd90232ce0cccb4f44728d2 to your computer and use it in GitHub Desktop.
Message box with per char printing
// Message box
const lines = []
const mbs = {
index: 0,
timer: null,
currentText: null
}
const mb = document.querySelector('.bord')
mb.addEventListener('click', mbp)
const mbn = document.createElement('div')
mbn.className = 'next'
mbn.innerHTML = '▶'
mb.appendChild(mbn)
mb.querySelectorAll('p').forEach(line => {
line.style.display = 'none'
lines.push(line)
})
if (lines.length) mbu()
function mbu () {
const l = lines[mbs.index]
mbs.currentText = l.innerHTML
l.innerHTML = ' '
printSentence(l, mbs.currentText)
l.style = 'block'
}
function mbp () {
if (mbs.timer) {
clearInterval(mbs.timer)
mbs.timer = null
lines[mbs.index].innerHTML = mbs.currentText
return
}
mbs.index = (mbs.index + 1) % lines.length
lines.forEach(line => line.style.display = 'none')
mbu()
}
function printSentence(element, sentence) {
let index = 0
mbs.timer = setInterval(() => {
const char = sentence[index]
if (char === '<') {
index = sentence.indexOf('>', index)
} else if (char === '&') {
index = sentence.indexOf(';', index)
}
element.innerHTML = sentence.slice(0, index)
if (index++ === sentence.length) {
clearInterval(mbs.timer)
mbs.timer = null
}
}, 30)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment