Created
August 5, 2022 21:46
-
-
Save nuel/85a44c3efdd90232ce0cccb4f44728d2 to your computer and use it in GitHub Desktop.
Message box with per char printing
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
// 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