How to change the position of the table of contents in rmarkdown?

You can use JQuery to relocate the TOC to an arbitrary position in the file. Simply insert a heading where you want the TOC to go, and use the ID generated by rendering the R Markdown file. For example:

<script>
  // Move TOC to the Table of Contents heading (with id "table-of-contents")
  $(function() {
    $( "#TOC" ).insertAfter( $( "#table-of-contents" ) );
  });
</script>

A heading called "Table of Contents" somewhere in the R Markdown file will receive id "table-of-contents". The TOC has id "TOC". The Jquery bit above selects that TOC, and inserts it after the "Table of contents" heading, wherever in the document it's located.


The position of the TOC is fixed in the R Markdown default HTML template. If you want to change its position in the document, you'll need to modify the template:

  1. Make a copy of the R Markdown HTML template to use as a starting point. You can find it by running this R command: system.file("rmd/h/default.html", package="rmarkdown")
  2. Move the $toc section to where you want the table of contents to appear.
  3. Save the modified template in the same folder as the document you're rendering as e.g. lowertitle.html
  4. Add template: lowertitle.html to the html_document settings.

From the standpoint of the template, all of the document's content is an atomic unit, so it might be necessary to put any content you want to appear before the TOC in the template itself.