Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay

JeffreyWay/app.js

Last active Nov 19, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.