Search code examples
htmlrquarto

How to prevent downloadthis button in Quarto HTML report from jumping to top of page on click?


I have a lengthy Quarto HTML report with several downloadthis buttons. When clicking each button, however, the browser jumps to the top of the screen. I've observed this in both Chrome and Firefox. How do I prevent/suppress this behavior?

Reproducible .qmd gist here.

Edit:

---
title: "downloadthis reprex"
format: html
---


<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

```{r}
library(downloadthis)
mtcars %>%
  download_this(
    output_name = "mtcars data set",
    output_extension = ".csv",
    button_label = "Download data",
    button_type = "warning",
    has_icon = TRUE,
    icon = "fa fa-save"
  )
```

Solution

  • One possible solution to this problem is to add the button id (which we need to add by id argument of download_this) to the download link embedded by {downloadthis}.

    ---
    title: "downloadthis reprex"
    format: html
    include-after-body: button.html
    ---
    
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    <br>
    
    ```{r}
    library(downloadthis)
    mtcars %>%
      download_this(
        output_name = "mtcars data set",
        output_extension = ".csv",
        button_label = "Download data",
        button_type = "warning",
        has_icon = TRUE,
        icon = "fa fa-save",
        id = 'mtcars-btn' # add an id to this button
      )
    ```
    

    button.html

    <style>
      #mtcars-btn:focus,
      #mtcars-btn:active  {
         box-shadow: none !important;
      }
      
      #mtcars-btn:hover {
         transition: 0.2s;
         filter: brightness(0.90);
      }
      
      #mtcars-btn:active {
         filter: brightness(0.80);
    }
    </style>
    
    <script>
      function add_href() {
        let mtcars_a = document.querySelector("a:has(#mtcars-btn)");
        mtcars_a.href = '#mtcars-btn';
      }
      
      window.onload = add_href;
    </script>
    

    Make sure to place both of the qmd file and button.html files in the same directory or even if placed in a different directory, make the appropriate changes in include-after-body accordingly.