1
votes

Does anyone have a way in a floating table of contents in an R markdown html document to create a button in the table of contents to collapse 3rd or 2nd level outcome headings? I use 3rd level subheadings for figure descriptions so that I get an automatic "table of figures" inside the TOC but sometimes don't want to see them when there are many figures.

I want to have toc_depth=3 in the yaml header and have the floating TOC initially open with all three levels shown, but have the option to click somewhere so that only 2 levels are shown in the TOC. Ideally it would be nice to also be able to display only one level, and to selectively expand a specific top-level heading to include second level headings (then third level, etc.).

1
Just seeking some clarification. So you'd still like the figure descriptions to appear in the TOC? But have the option of collapsing them with the button? That is, using something like toc_depth: 2 in the YAML header of the .Rmd file is NOT what you are after?markdly
Good question. I've updated the question to clarify.Frank Harrell

1 Answers

4
votes

Well, I've had a go and got something to work by adding a small javascript function to the bottom of the RMarkdown file. Whether this fits the use case I'm not sure! This is the full contents of the .Rmd file:

Edit

Extra button added to collapse level 3 headings only in response to comments

---
output:
  html_document:
    toc: true
    toc_float:
      collapsed: true
---

# Chapter 1

## Section 1-1

### Figure 1-1-1

### Figure 1-1-2

# Chapter 2

## Section 2-1

### Figure 2-1-1

### Figure 2-1-2

---

Select the menu on the left to expand / collapse table of contents (TOC)
entries. Press button below to collapse all TOC except the top level headings.

<button id="btnCollapseHeading" onclick="collapseTOC()">Collapse sub-headings</button>

If you only want to collapse level 3 headings press this button.

<button id="btnCollapseLevel3" onclick="collapseLevel3()">Collapse Level 3 only</button>

<script>
function collapseTOC() {
  var x = document.getElementsByClassName("tocify-subheader");
  var i;
  for (i = 0; i < x.length; i++) {
      x[i].style.display = "none";
  }
}

function collapseLevel3() {
  var x = document.getElementsByClassName("tocify-subheader");
  var i;
  for (i = 0; i < x.length; i++) {
      if (x[i].getAttribute("data-tag") == "3") {
        x[i].style.display = "none";
      }
  }
}

</script>

I've also added an example to try out at https://github.com/markdly/rmd-toc-button