Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Shiny DataTable selected row color

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.

like image 458
James Allingham Avatar asked Jul 07 '17 09:07

James Allingham


1 Answers

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

like image 61
Pork Chop Avatar answered Nov 18 '22 08:11

Pork Chop