7

I am trying to set the highlight color for a selected row in a DataTable in my shiny app. Basically I want the color of selected rows to be say red rather than blue. However, I am not at all familiar with JavaScript so I am struggling to write the appropriate callback (at least I think that is the problem). Here is what I've tried so far:

# ui.R
library(shiny)

fluidPage(
  title = 'DataTables Test',
  DT::dataTableOutput('table')
)

# server.R
library(shiny)
library(DT)

# render the table
output$table = renderDataTable(datatable(head(iris, 20), 
options = list(
    initComplete = JS(
      "function(settings, json) {",
      "var rows = $(this.api().table().rows());",
      "for (var i = 0; i < rows.length; i++){ ",
      "var row = rows[i];",
      "row.css({'background-color': '#000', 'color': '#f00'})",
      "}",
      "}")
  )))

})

As you can see, so far I am just trying to figure out how to change the row colors. Once I had figured this out I was going to try and change the css to something like:

"tr.selected td, table.dataTable td.selected { background-color: #f00}"

But I haven't gotten there yet - unfortunately the code above doesn't do anything to the background color. If anyone could help me with the whole solution that would be great.

James Allingham
  • 666
  • 1
  • 7
  • 26

1 Answers1

18

This should do the job:

#rm(list = ls())
library(shiny)
library(DT)

ui <- basicPage(
  tags$style(HTML('table.dataTable tr.selected td, table.dataTable td.selected {background-color: pink !important;}')),
  mainPanel(DT::dataTableOutput('mytable'))
)

server <- function(input, output,session) {

  output$mytable = DT::renderDataTable(    
    datatable(mtcars)
  ) 
}
runApp(list(ui = ui, server = server))

enter image description here

Pork Chop
  • 26,081
  • 5
  • 59
  • 70
  • 2
    Thank you very much for the above, it helped me with a similar problem. To set different colours for selected rows and columns, use: `tags$style(HTML('table.dataTable tr.selected td{background-color: pink !important;}')), tags$style(HTML('table.dataTable td.selected {background-color: orange !important;}'))` – Hester Lyons Mar 02 '18 at 10:39