-
-
Save cferdinandi/5817d911130649f72fa88f8a61fd7a30 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Automatic Night Mode</title> | |
<style type="text/css"> | |
body { | |
margin: 0 auto; | |
max-width: 40em; | |
width: 88%; | |
} | |
.night body { | |
background-color: #001f3f; | |
color: white; | |
} | |
.transitional body { | |
background-color: #f7f7f7; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Automatic Night Mode</h1> | |
<p id="greeting"></p> | |
<script> | |
// | |
// Variables | |
// | |
// Get the time right now | |
var now = new Date().getHours(); | |
// Get the #greeting element | |
var greeting = document.querySelector('#greeting'); | |
// | |
// Methods | |
// | |
/** | |
* Get the greeting based on time | |
* @return {String} The greeting | |
*/ | |
var getGreeting = function () { | |
if (now > 20) return 'Good night!'; // If it's after 8pm | |
if (now > 17) return 'Good evening!'; // If it's after 5pm | |
if (now > 11) return 'Good afternoon!'; // If it's after noon | |
return 'Good morning!'; // Default message | |
}; | |
/** | |
* Adjust the color theme based on time | |
*/ | |
var adjustColorMode = function () { | |
// Remove any existing classes | |
document.documentElement.classList.remove('transitional'); | |
document.documentElement.classList.remove('night'); | |
// If it's nighttime, go dark mode | |
if (now > 20) { | |
document.documentElement.classList.add('night'); | |
return; | |
} | |
// If it's morning or evening, go transitional | |
if (now > 17 || now < 11) { | |
document.documentElement.classList.add('transitional'); | |
} | |
}; | |
/** | |
* Add a greeting and adjust the color palette | |
*/ | |
var updateUI = function () { | |
// Set the greeting | |
greeting.textContent = getGreeting(); | |
// Update color palette | |
adjustColorMode(); | |
}; | |
// | |
// Inits | |
// | |
// Update the UI on page load | |
updateUI(); | |
// Check again every 15 minutes | |
setInterval(function () { | |
now = new Date().getHours(); | |
updateUI(); | |
}, 1000 * 60 * 15); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment