Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created March 1, 2019 05:39
Show Gist options
  • Save joduplessis/7dd5163356ba57c0cbf2d65ad1c083cb to your computer and use it in GitHub Desktop.
Save joduplessis/7dd5163356ba57c0cbf2d65ad1c083cb to your computer and use it in GitHub Desktop.
Helped a friend do a fade out/in testmassessment in vanilla JS.
<html>
<body>
<style>
* {
font-family: helvetica;
}
.fadein {
transition: opacity 1s;
opacity: 1;
}
.fadeout {
transition: opacity 1s;
opacity: 0;
}
</style>
<div id="div1" class="fadein">One</div>
<div id="div2" class="fadein">Two</div>
<div id="div3" class="fadein">Three</div>
<div id="div4" class="fadein">Four</div>
<script>
let needle = 0;
const length = 1000; // <- 1 second
const elements = ["div1", "div2", "div3", "div4"];
const fadeOut = (arrayPosition) => {
const elementId = elements[arrayPosition];
const element = document.getElementById(elementId);
// function that fades element out
// Add className for CSS fadeout
// Animation length is 100ms
element.className = "fadeout";
setTimeout(() => {
// Fade it back in so it doesn't look weird
element.className = "fadein";
// Increment the needle to get the next div
needle++;
// Start form the beginning if it's reached the end
if (needle == elements.length) needle = 0;
// Call this same function to fadeout the next div
fadeOut(needle);
}, length);
}
</script>
<br/>
<button onClick="javascript:fadeOut(0)">Start!</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment