Zurb Foundation 6 Dark mode example

How to set up your Zurb Foundation 6 for sites with dark mode support.

by Vino Rodrigues

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/what-input/5.2.7/what-input.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.6.3/js/foundation.js"></script>
<div class="grid-container">
	<div class="grid-x grid-margin-x">
		<div class="cell small-12">
			<br style="margin-top:3rem">
			<div class="large callout">
				<h4>Test It Out</h4>
				<button id="toggleButton" class="large primary button">Toggle</button>
				<blockquote>In <b id="mode-msg">browser default</b> mode, you are. <cite>Yeti</cite></blockquote>
			</div>
		</div>
	</div>
</div>

JavaScript

$(document).ready(function() {
	$(document).foundation();

	// based on the Rule of Thumb, load the brand alternative first, and then the brand preference
	// - then let the browser decide - (and if it doesn't then the latter wins)
	// This bit is usally in your <head> ... just doing it like this here so that we can make it work in jsFiddle
	$('head').append('<link id="css-dark" rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/vinorodrigues/[email protected]/dist/dark/foundation.min.css" media="(prefers-color-scheme: dark)" />');
	$('head').append('<link id="css-light" rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.6.3/css/foundation.css" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: light)" />');
	$('head').append('<link id="css" />');

	// the big toggle switch and all it's trickery - it assumes jQuery is loaded.
	// if jQuery loaded, set the button control trigger
	$("#toggleButton").click( function() {
		// get current mode
		$mode = $("#css").attr("data-mode");  // don't use data("mode"), it doesn't refresh
		if (typeof $mode === 'undefined') {
			// not defined yet - set brand pref. & ask the browser if alt. is active
			$mode = 'light';
			if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) $mode = 'dark';
			// optional disable media-query entries
			$("#css-dark").prop( "disabled", true );
			$("#css-light").prop( "disabled", true );
		}

		// by here we have the current mode, so swap it
		$mode = ($mode == 'dark') ? 'light' : 'dark';
		// and grab the new mode css href
		$href = $("#css-"+$mode).attr("href");

		// set the css the forced preference.
		$("#css").attr( {
			"rel" : "stylesheet",
			"type": "text/css",
			"href": $href,
			"data-mode": $mode,
			} );

		// optional bit, just for this demo
		$("#mode-msg").html( $mode );
	} );
});