Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Activate dark mode if 'prefers-color-scheme: dark' is supported and preferred, and/or toggle the dark mode using a button.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HMTL template</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* just to see a nicer demo */
@import url("https://unpkg.com/normalize.css");
body {
padding: 0 2rem 2rem 2rem;
font-family: sans-serif;
}
button {
padding: 1rem 2rem;
cursor: pointer;
}
/* add a basic dark color combination */
body.dark {
background-color: black;
color: white;
}
</style>
</head>
<body>
<h1>Hello!</h1>
<button class="dark-mode-switcher" type="button" value="Toggle dark mode">
Dark or light?
</button>
<script src="https://unpkg.com/jquery"></script>
<script>
// activate dark mode if 'prefers-color-scheme: dark' is supported and preferred
// ..or toggle dark mode using a button
// https://web.dev/prefers-color-scheme/
var prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
$(function() {
if (prefersDark) {
$('body').addClass('dark');
}
$('.dark-mode-switcher').on('click', function(e) {
$('body').toggleClass('dark');
e.preventDefault();
});
});
</script>
</body>
</html>
@marcop135

This comment has been minimized.

Copy link
Owner Author

marcop135 commented Jan 14, 2020

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.