Skip to content

Commit

Permalink
Hack element toggler into Quarto theme switching code
Browse files Browse the repository at this point in the history
  • Loading branch information
effigies committed Jun 5, 2023
1 parent da80284 commit dcd480f
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 5 deletions.
2 changes: 2 additions & 0 deletions _quarto.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ format:
dark: darkly
css: styles.css
toc: true
include-in-header:
- toggle.js



10 changes: 5 additions & 5 deletions index.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ format:
page-layout: full
---

<center><a>
<picture>
<source srcset="images/stanford-line2-8-dark.png" media="(prefers-color-scheme: dark)" />
<img src="images/stanford-line2-8.png" alt="Poldracklab logo" width="50%" />
</picture></a>
<center>
<a>
<img src="images/stanford-line2-8.png" alt="Poldracklab logo" width="50%" class="only-light" />
<img src="images/stanford-line2-8-dark.png" alt="Poldracklab logo" width="50%" class="only-dark" style="display: none" />
</a>
</center>

<br>
Expand Down
42 changes: 42 additions & 0 deletions toggle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<script id="toggle-light-dark-elements" type="application/javascript">
/* Extend Quarto theme toggling to allow elements to be displayed/hidden in light/dark themes */

// Replicated from https://github.com/quarto-dev/quarto-cli/blob/84d4659/src/resources/formats/html/templates/quarto-html.ejs
const getColorSchemeSentinel = () => {
const localAlternateSentinel = 'alternate';
if (window.location.protocol !== 'file:') {
const storageValue = window.localStorage.getItem('quarto-color-scheme');
return storageValue != null ? storageValue : localAlternateSentinel;
} else {
return localAlternateSentinel;
}
};

// Function to toggle light and dark elements based on color scheme
const toggleColorSchemeElements = () => {
const scheme = getColorSchemeSentinel();
const lightElements = document.getElementsByClassName('only-light');
const darkElements = document.getElementsByClassName('only-dark');

for (var i = 0; i < lightElements.length; i++) {
lightElements[i].style.display = scheme == 'default' ? 'block' : 'none';
}
for (var i = 0; i < darkElements.length; i++) {
darkElements[i].style.display = scheme == 'default' ? 'none' : 'block';
}
};

// Add event listener for when the readyState is complete (and default toggler is set)
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
// Toggle scheme once
toggleColorSchemeElements();
// Append our toggle function to the old one
const oldToggle = window.quartoToggleColorScheme;
window.quartoToggleColorScheme = () => {
oldToggle();
toggleColorSchemeElements();
}
}
});
</script>

0 comments on commit dcd480f

Please sign in to comment.