Created
May 21, 2020 09:46
-
-
Save leegee/b385ed1cfefbe43dc24a8a2422b8bfb3 to your computer and use it in GitHub Desktop.
Cycle quotes with CSS fade
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
<div id='frontpage-quote'></div> |
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
.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} | |
} |
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
// 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