Skip to content

Instantly share code, notes, and snippets.

@tai221
Forked from JeffreyWay/app.js
Created November 28, 2022 17:42
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 tai221/013105202f60b0e1b05af2a6db2e8380 to your computer and use it in GitHub Desktop.
Save tai221/013105202f60b0e1b05af2a6db2e8380 to your computer and use it in GitHub Desktop.
Swappable Heading example
class SwappableHeading {
constructor(element, headings = []) {
this.element = element;
this.headings = headings;
this.current = 1;
}
async swap() {
while (true) {
await this.wait(2000);
await this.clear();
await this.type(this.nextHeading());
}
}
async type(text) {
while (text.length) {
await this.append(text[0]);
text = text.substring(1);
}
}
text() {
return this.element.innerHTML;
}
append(text) {
this.element.innerHTML += text;
return this.wait(100);
}
async clear() {
while (this.length()) {
await this.backspace();
}
}
backspace() {
this.element.innerHTML = this.text().slice(0, -1);
return this.wait(100);
}
nextHeading() {
let heading = this.headings[this.current - 1];
this.increment();
return heading;
}
empty() {
return this.length() === 0;
}
length() {
return this.text().length;
}
increment() {
this.current++;
if (this.current > this.headings.length) {
this.current = 1;
}
}
async wait(milliseconds) {
return new Promise(resolve => {
setTimeout(resolve, milliseconds);
});
}
}
<!doctype html>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
<section class="bg-gradient-to-br from-blue-500 to-blue-700 h-screen grid place-items-center">
<h1 class="font-bold text-white text-6xl uppercase tracking-widest">Laracasts</h1>
</section>
<script src="/js/app.js"></script>
<script>
new SwappableHeading(
document.querySelector('h1'),
['It', 'Should', 'Work']
).swap();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment