Skip to content

Instantly share code, notes, and snippets.

@leegee
Created May 21, 2020 09:46
Show Gist options
  • Save leegee/b385ed1cfefbe43dc24a8a2422b8bfb3 to your computer and use it in GitHub Desktop.
Save leegee/b385ed1cfefbe43dc24a8a2422b8bfb3 to your computer and use it in GitHub Desktop.
Cycle quotes with CSS fade
<div id='frontpage-quote'></div>
.quote {
animation: fade 3s;
-webkit-animation: fade 3s;
-moz-animation: fade 3s;
}
@keyframes fade {
0% {opacity:0}
30% {opacity:1}
70% {opacity:1}
100% {opacity:0}
}
@-moz-keyframes fade {
0% {opacity:0}
30% {opacity:1}
70% {opacity:1}
100% {opacity:0}
}
@-webkit-keyframes fade {
0% {opacity:0}
30% {opacity:1}
70% {opacity:1}
100% {opacity:0}
}
// frontpage-quotes.js
const htmlQuotes = [];
let quoteContainer;
let quoteIndex;
const showQuote = () => {
quoteIndex++;
if (quoteIndex >= htmlQuotes.length) {
quoteIndex = 0;
}
const quoteEl = document.createElement('div');
quoteEl.onanimationend = (e) => {
quoteEl.parentNode.removeChild(quoteEl);
showQuote();
};
quoteEl.innerHTML = htmlQuotes[quoteIndex];
quoteEl.className = 'quote';
quoteContainer.appendChild(quoteEl);
}
// https://javascript.info/task/shuffle
const shuffle = (array) => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const loadFrontpageQuoteRand = async () => {
const res = await fetch('quotes.json');
const _quotes = await res.json();
const quotes = shuffle(_quotes);
quoteContainer = document.getElementById('frontpage-quote');
if (quotes) {
quotes.forEach(quote => htmlQuotes.push(quote.split(/[\n\r\f]+/).join('<br>')));
quoteIndex = Math.floor(Math.random() * htmlQuotes.length);
showQuote();
}
}
document.addEventListener('DOMContentLoaded', loadFrontpageQuoteRand);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment