3

I have a Quarto document which is rendered to HTML. In that document, I use .panel-tabset to create tabbed panels with code examples in different languages: R and Python.

How can I create a single button that switches all the tabs on a given page?

In this minimal document, I would like the "global" button to switch all .panel-tabset to R or Python at the same time, instead of having to click on each individual tab.

---
title: Panel tabset
---

First example:

::: {.panel-tabset}
# R
```{r}
2 + 2
```
# Python
```{python}
2 + 2
```
:::

Second example:

::: {.panel-tabset}
# R
```{r}
1 + 2
```
# Python
```{python}
1 + 2
```
:::
Vincent
  • 15,809
  • 7
  • 37
  • 39

1 Answers1

2

I can offer the following implementation which simply toggles the currently active panes.

toggle-tabs.html

<style type="text/css">
  div.quarto-title {
    display: grid;
    grid-template-columns: 3fr 1fr;
  }
  
  button#toggleTabsButton {
    border-radius: 10px;
    font-size: smaller;
    font-family: monospace;
  }
</style>

<script type="text/javascript">
  function toggle_tabset() {
    const tab_links = document.querySelectorAll('div.panel-tabset a.nav-link');
    tab_links.forEach(tab => {
        tab.classList.toggle('active');
        let aria_val = tab.getAttribute('aria-selected');
        let toggle_val = aria_val === 'true' ? 'false' : 'true';
        tab.setAttribute('aria-selected', toggle_val);
    });
    const tab_panes = document.querySelectorAll('div.tab-content div.tab-pane')
    tab_panes.forEach(pane => { 
      pane.classList.toggle('active');
    });
  };
  
  window.document.addEventListener("DOMContentLoaded", function (event) {
    let title = document.querySelector('div.quarto-title h1.title');
    const button = document.createElement('button');
    button.id = 'toggleTabsButton';
    button.textContent = 'Toggle R/Python Code';
    title.insertAdjacentElement('afterend', button);
    button.addEventListener('click', toggle_tabset);
  });
</script>

document.qmd

---
title: Panel tabset
include-after-body: toggle-tabs.html
---

First example:

::: {.panel-tabset}
# R
```{r}
2 + 2
```
# Python
```{python}
2 + 2
```
:::

Second example:

::: {.panel-tabset}
# R
```{r}
1 + 2
```
# Python
```{python}
1 + 2
```
:::

toggle button

shafee
  • 15,566
  • 3
  • 19
  • 47