Vincent
Vincent

Reputation: 17785

Quarto document with `.panel-tabset`: How to flip all tabs with a single button?

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
```
:::

Upvotes: 5

Views: 1333

Answers (2)

Corrado
Corrado

Reputation: 755

https://quarto.org/docs/output-formats/html-basics.html#tabset-groups, simply add a group="<group_name>" statement to the panel options

---
title: Panel tabset
---

First example:

::: {.panel-tabset group="language"}
# R
```{r}
2 + 2
```
# Python
```{python}
2 + 2
```
:::

Second example:

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

Upvotes: 3

Shafee
Shafee

Reputation: 20007

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

Upvotes: 2

Related Questions