7

Use case

I use R and Knitr a lot to produce long html reports. The reports contain headers by using the markdown # syntax. These headers give good orientation for the reader's navigation...

Problem

... but the reports sometimes get very long. Scrolling from beginning to the end take very long time. Readers of the reports get annoyed seeing all the report content before reaching the relevant parts.

Question

Is there a way to implement in Knitr a collapsing and expanding header element? Example

Requirements

  • By default the header shall be collapsed. Only by clicking the contents below the header shall expand. This would tremendously help to keep the reports small in appearance and facilitate easy and fast navigation.
  • In order to give the reader feedback of the state the header it shall represent it's state. I recommend something along the mechanism used in Wikipedia (see image above).
user2030503
  • 3,064
  • 2
  • 36
  • 53
  • The issue is going to be that you'll have to manually add the `show`/`hide` buttons after `knit`ing. You may want to just add a table of contents, [as described here](http://stackoverflow.com/questions/14662626/set-page-width-in-knitr-for-md-or-html-output). – Thomas Dec 22 '13 at 15:55

1 Answers1

4

You can make elements collapse using Javascript. The jQuery JavaScript framework makes this reasonably easy via the hide and show methods.

In the folder that contains your Rmd template, create a subfolder named script and save the jQuery file in it. (Doesn't have to be there, but that's a reasonably standard location.)

Add this code near the top of your Rmd file.

<script type="text/javascript" language="javascript" src="script/jquery-1.10.2.min.js">
</script>

For Markdown, the closing tag needs to be on a separate line.

Alternatively, if your report is mostly going to be read on machines where there is internet access, you can should use a Google-hosted version of jQuery.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" >
</script>

Then add another script block for your collapsing logic. The exact implementation is up to you; there are lots of examples on the internet.

The key to making your collapsing/expanding logic simple is to make sure that the elements you are manipulating have a consistent class (or a pattern to their ids).

Community
  • 1
  • 1
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • Looks like, the markdown syntax of Knitr (i.e. # for header level 1) will not easily combine with the jQuery techniques being suggested. – user2030503 Dec 20 '13 at 19:06