Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rmarkdown : is it possible to display the TOC of the current tab only in a tabset

The title says it all...

If I have an R-markdown document structured like this

# TITLE { .tabset }

## First tab : mammals

### rabbits

### dogs

### elephants

## Second tab : birds

### sparrows

### swallows

I would like the TOC to display only the items "rabbits, dogs, elephants" when the first tab is active, an only "sparrows, swallows" when then second tab is active.

Many thanks in advance

like image 995
Elvis Avatar asked Jan 29 '26 09:01

Elvis


1 Answers

This might not be the easiest solution, but it should work, even when you have sections with the same name on different tab panels. It is tailored to your MRE, so adjustments might have to be done depending on your real application.

I used Javascript to achieve what you want. Just add the code at the beginning of your rmarkdown document.

I hope the comments make it clear enough what is happening.

<script type="text/javascript">
$(document).ready(function() {
  var $tocItems = $(".tocify-subheader li.tocify-item"); // selector for all TOC items
  var $tabs     = $("a[role=\"tab\"]");                  // selector for all tabs
  var $panels   = $("div[role=\"tabpanel\"]");           // selector for all tabpanels

  $tocItems.hide();  // hide all TOC items

  // get the tab name for each section header (e.g. mammals)
  // and assign it to its corresponding toc item
  $panels.find("div[data-unique]").each(function() {
    var key = $(this).attr("data-unique");
    var tab = $(this).closest("div[role=\"tabpanel\"]").attr("id");
    $tocItems.filter("[data-unique=\"" + key + "\"]").attr("tab", tab)
  })
  // now each toc item knows to which tab panel it is pointing

  // show the toc items that point to sections on the first panel
  $tocItems.filter(function() {
    return($(this).attr("tab") === $tabs.first().text());
  }).toggle();

  // assign an onclick event to the tabs..
  $tabs.on("click", function() {
    $tocItems.hide();  // ... hide all TOC items
    var key = $(this).text(); // ... get the name of the tab clicked
    $tocItems.filter(function() {  // ... filter for the toc items pointing to that tab
      return($(this).attr("tab") === key);
    }).toggle();  // ... and show them
  });  
});
</script>
like image 183
Martin Schmelzer Avatar answered Jan 31 '26 23:01

Martin Schmelzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!