Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Collapsible Code Output for `xaringan`
<script>
(function() {
var divHTML = document.querySelectorAll(".details-open");
divHTML.forEach(function (el) {
var preNodes = el.getElementsByTagName("pre");
var outputNode = preNodes[1];
outputNode.outerHTML = "<details open class='output'><summary>Output</summary>" + outputNode.outerHTML + "</details>";
})
})();
(function() {
var divHTML = document.querySelectorAll(".details");
divHTML.forEach(function (el) {
var preNodes = el.getElementsByTagName("pre");
var outputNode = preNodes[1];
outputNode.outerHTML = "<details class='output'><summary>Output</summary>" + outputNode.outerHTML + "</details>";
})
})();
</script>
---
output:
xaringan::moon_reader:
includes:
after_body: "collapseoutput.js"
---
### This output is closed first
.details[
```{r}
summary(cars)
```
]
### This output is open first
.details-open[
```{r}
str(cars)
```
]
@emitanaka

This comment has been minimized.

Copy link
Owner Author

emitanaka commented Jul 20, 2019

Untitled 2019-07-20 14_45_57

@emitanaka

This comment has been minimized.

Copy link
Owner Author

emitanaka commented Jul 20, 2019

Note you need to break up the chunk so there is only one output per .details (or .details-open).
E.g.

.details[
 ``{r}
summary(cars)
str(cars)
``
]

would hide only for the first code output (i.e. output for summary(cars)) but not for output of str(cars).

@OmaymaS

This comment has been minimized.

Copy link

OmaymaS commented Jul 20, 2019

I used to write pure html in .rmd like:

<details>
    <summary>
    Click to expand
    </summary>
    ```{r}
    summary(cars)
    ```
</details>

So just was curious about the advantage of wrapping this in JS functions? is it for better reusability and compact code?

@emitanaka

This comment has been minimized.

Copy link
Owner Author

emitanaka commented Jul 21, 2019

@OmaymaS It actually doesn't work for xaringan, I think because remark.js processes the R markdown output in a different way within html code as opposed to markdown code. Also by doing that it would fold the code itself too while this folds only the output alone.

@OmaymaS

This comment has been minimized.

Copy link

OmaymaS commented Jul 21, 2019

Thanks for the clarification :)

@seasmith

This comment has been minimized.

Copy link

seasmith commented Jul 22, 2019

Can the details/details-open class be specified with chunk option class.source?

@emitanaka

This comment has been minimized.

Copy link
Owner Author

emitanaka commented Jul 22, 2019

@seasmith not for xaringan because it's processed by remark.js instead of Pandoc (from what I understand)

@emitanaka

This comment has been minimized.

Copy link
Owner Author

emitanaka commented Aug 1, 2019

See alternative and more concise JS by @yihui here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.