Bootstrap 5.3.0 introducted the concept of a theme to set the color mode of a website, ostensibly support light color mode and dark color mode.
The examples on the Bootstrap website show how to manually switch between modes but I wanted a way to automatically set the mode based on the operating system setting when the site loaded, and automatically switch the mode when the operating system switched from one mode to another.
So I put together an anonymous function which does the first and a window watcher which does the second.
This JavaScript should be included in the page itself, putting it in a separate file will cause the page to visibly switch modes when it is loaded which is pretty ugly.
<script type="text/javascript">
////////////////////////////////////////////////
//
// Anonymous function to set the Bootstrap
// color theme before the page fully loads
//
(function() {
// Create a new mutation observer
const mutationObserver = new MutationObserver(function() {
// We have a document body
if ( document.body ) {
// Get the browser color theme
const colorTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
// Log
console.log('base: initial colorTheme [' + colorTheme + ']');
// Set the Bootstrap color theme
if ( colorTheme == 'dark' ) {
document.body.setAttribute('data-bs-theme', 'dark')
}
else {
document.body.removeAttribute('data-bs-theme')
}
// Disconnect the mutation observer, no longer needed
mutationObserver.disconnect();
}
});
// Set the mutation observer
mutationObserver.observe(document.documentElement, {childList: true});
})();
////////////////////////////////////////////////
//
// Window watcher to switch Bootstrap color theme
//
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
// Get the browser color theme
const colorTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
// Log
console.log('base: switch colorTheme [' + colorTheme + ']');
// Set the Bootstrap color theme
if ( colorTheme == 'dark' ) {
document.body.setAttribute('data-bs-theme', 'dark')
}
else {
document.body.removeAttribute('data-bs-theme')
}
});
</script>