Search code examples
rgtquarto

Start very wide table scrolled to the right in gt and quarto


I don't even quite know how to start researching this but say I have a table that is very wide. If I were to render that table using {gt} in Quarto you get a handy scroll bar at the bottom of the table so you can scroll across the table.

---
title: "wide-tables"
format: html
execute: 
  echo: false
  warning: false
---

```{r}
library(dplyr)
library(tidyr)
library(gt)

table <- quakes %>% 
  group_by(stations) %>% 
  summarise(mag = mean(mag)) %>%
  pivot_wider(
    names_from = stations, 
    values_from = mag
)

gt(table)
```

My question: is there any way to have that scroll bar default to all the way to the right?


Solution

  • You can use some javascript code to do this. And to do this for a specific table, wrap the code chunk (which will generate the gt table) with pandoc divs specifying a css class wide_tab.

    ---
    title: "wide-tables"
    format: html
    execute: 
      echo: false
      warning: false
    include-after-body: scrollbar_start.html
    ---
    
    ::: {.wide_tab}
    
    ```{r}
    library(dplyr)
    library(tidyr)
    library(gt)
    
    table <- quakes %>% 
      group_by(stations) %>% 
      summarise(mag = mean(mag)) %>%
      pivot_wider(
        names_from = stations, 
        values_from = mag
    )
    
    gt(table)
    ```
    
    :::
    

    scrollbar_start.html

    <script>
      function scrollbar_starting() {
        let gt_table = document.querySelector(".wide_tab .gt_table");
        let parent = gt_table.parentElement;
        let width = parent.scrollWidth;
        parent.scrollLeft = width;
      }
      
      window.onload = scrollbar_starting();
    </script>
    

    a super wide egt table with scrollbar starting at right side