How to hide code in RMarkdown, with option to see it
This has been made much easier with the rmarkdown package, which did not exist three years ago. Basically you just turn on "code folding": https://bookdown.org/yihui/rmarkdown/html-document.html#code-folding. You no longer have to write any JavaScript.
E.g.
---
title: "Habits"
output:
html_document:
code_folding: hide
---
Also see https://bookdown.org/yihui/rmarkdown-cookbook/fold-show.html for more control over which code blocks to be fold or unfold.
If you add an html tag before your code you can use CSS selectors to do clever things to bits of the output - markdown handily passes the HTML through:
<style>
div.hidecode + pre {display: none}
</style>
<div class="hidecode"></div>
```{r}
summary(cars)
```
Here my CSS style rule matches the first <pre>
tag after a <div class=hidecode>
and sets it to be invisible. Markdown writes the R chunk with two <pre>
tags - one for the R and one for the output, and this CSS catches the first one.
Now you know how to match the code and output blocks in CSS, you can do all sorts of clever things with them in Javascript. You could put something in the <div class=hidecode>
tag and add a click event that toggles the visibility:
<style>
div.hidecode + pre {display: none}
</style>
<script>
doclick=function(e){
e.nextSibling.nextSibling.style.display="block";
}
</script>
<div class="hidecode" onclick="doclick(this);">[Show Code]</div>
```{r}
summary(cars)
```
The next step in complexity is to make the action toggle, but then you might as well use jQuery
and get real funky. Or use this simple method. Let's do it with a button, but you also need a div to get your hooks into the R command PRE block, and the traversal gets a bit complicated:
<style>
div.hideme + pre {display: none}
</style>
<script>
doclick=function(e){
code = e.parentNode.nextSibling.nextSibling.nextSibling.nextSibling
if(code.style.display=="block"){
code.style.display='none';
e.textContent="Show Code"
}else{
code.style.display="block";
e.textContent="Hide Code"
}
}
</script>
<button class="hidecode" onclick="doclick(this);">Show Code</button>
<div class="hideme"></div>
```{r}
summary(cars)
```
( Note: I thought you could wrap R chunks in <div>
tags:
<div class="dosomething">
```{r}
summary(cars)
```
</div>
but that fails - anyone know why?)