Rmarkdown 'saving' an exact place of the html page

Viewed 65

I've created two Rmarkdown pages that are linked together. I'd like to know if there is a way to code that the links direct to a specific spot on each page.

---
title: "Page 1"
author: "--"
date: "22 9 2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

### Header

example text.

#### example plot 1.

```{r cars}
plot(cars)
```

more example text

#### example plot 2.

```{r pressure, echo=FALSE}
plot(pressure)
```

link to [Page 2](./Page-2.html)

And Page 2:

---
title: "Page 2"
author: "--"
date: "22 9 2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

### Header

example text.

#### example plot 1.

```{r cars}
plot(cars)
```

more example text

#### example plot 2.

```{r pressure, echo=FALSE}
plot(pressure)
```

[Page 1](./Page-1.html)

For example, I'd like the page 2 link to redirect straight to the second graph. Moreso, when clicking back to page 1 - is there a way for it to save the spot I was currently looking at? Thanks.

2 Answers

This feature is not provided for HTML output of rmarkdown/knitr. However, you can easily implement this using javaScript (jquery):

The idea is to include a small script that saves the last scroll position in a variable (I've called it ScrPos below) in local memory and restores the scroll position when the page is (re)loaded.

header.html

<script type="text/javascript">
  // check if ScrPos is available. If so, scroll to ScrPos
  $(function() {
    if (localStorage.ScrPos) {
      $(window).scrollTop(localStorage.ScrPos);
    }
  });

  // save last scroll position  to ScrPos before page unload
  $(window).on("beforeunload", function() {
    var ScrPos = $(window).scrollTop();
    localStorage.setItem("ScrPos", ScrPos);
  });
</script>

You may include header.html in the YAML header (of both) .rmd files like this:

output: 
  html_document:
    include:
      in_header: header.html

Note that header.html needs to be in the same directory as the .Rmd.

for the linking to the second graph part it can be easily achieved by using the div id that's used for the second graph, either by explicitly assigning it or by using transforming the spaced section title to a dash separated one `example plot 2.` => id = `example-plot-2.` i.e:

New code for page 2

#### example plot 2.{#second_graph}

```{r pressure, echo=FALSE}
plot(pressure)
```

[Page 1](./Page-1.html)

and then in page one simply add the id to the link i.e:

link to [pressure graph](./Page-2.html#second_graph)
Related