Collapsing / hiding figures in R markdown
I was able to get Lucy's code working for me, but I also think it's more useful and cleaner to have the outputs hidden by default. It's a very simple addition. Just execute jquery that clicks all the "Hide Output" buttons upon rendering. My code looks like this:
<script>
$( "input.hideshow" ).each( function ( index, button ) {
button.value = 'Hide Output';
$( button ).click( function () {
var target = this.nextSibling ? this : this.parentNode;
target = target.nextSibling.nextSibling;
if ( target.style.display == 'block' || target.style.display == '' ) {
target.style.display = 'none';
this.value = 'Show Output';
} else {
target.style.display = 'block';
this.value = 'Hide Output';
}
} );
} );
$("input.hideshow").click()
</script>
Only the last line before </script>
was the addition.
I have not been able to get the above solution (or others I found) to work consistently, but using the in-line html (Bootstrap example/solution) I found at W3schools.com works well in Rmarkdown.
I use it to show a simple plot in html output in the example below. It should work with any chunk output:
<button class="btn btn-primary" data-toggle="collapse" data-target="#BlockName"> Show/Hide </button>
<div id="BlockName" class="collapse">
```{r}
plot(mtcars$disp, mtcars$mpg)
```
</div>
note: If you use this on multiple sections, each one needs a unique id (ie replace BlockName
with a unique id for each section to be collapsed.)
If you add this to the end of your .Rmd
file
<script>
$( "input.hideshow" ).each( function ( index, button ) {
button.value = 'Hide Output';
$( button ).click( function () {
var target = this.nextSibling ? this : this.parentNode;
target = target.nextSibling.nextSibling.nextSibling.nextSibling;
if ( target.style.display == 'block' || target.style.display == '' ) {
target.style.display = 'none';
this.value = 'Show Output';
} else {
target.style.display = 'block';
this.value = 'Hide Output';
}
} );
} );
</script>
and then this before each chunk you want to have a toggle:
<input type=button class=hideshow></input>
(adapted from here: https://groups.google.com/forum/#!topic/knitr/d37E0mP3w6k)
Note: this will work if you show the code - if you are hiding the code (with echo = FALSE
), change
target = target.nextSibling.nextSibling.nextSibling.nextSibling;
to
target = target.nextSibling.nextSibling;
Note 2: if you want to use the code_folding
option, change
target = target.nextSibling.nextSibling.nextSibling.nextSibling;
to
target = target.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling;