Search code examples
rdatatable

Change BG color of DATATABLE


I want to change the color of background cell of the first and last row of this Datatable. How can i specify this in format_style() function?

df <- data.frame(categoria = c("A","B","C","D"),
                 posição = c(4,3,2,1))


DT::datatable(df)

Solution

  • You can use something like this - a mix of the DataTables API, jQuery and JavaScript:

    library(DT)
    
    df = data.frame(
      category = c("A","B","C","D"),
      position = c(4,3,2,1)
    )
    
    
    datatable(df, options = list(
      initComplete = JS(
        "function(settings, json) {",
        "  var allNodes = this.api().table().rows().nodes().toArray();",
        "  var firstLast = [ allNodes[0], allNodes[allNodes.length -1] ];",
        "  $(firstLast).css({'background-color': 'red', 'color': 'white'});",
        "}")
    ))
    

    Which results in the following:

    enter image description here


    But this depends on what exactly you mean by "first" and "last". With this approach (using initComplete), the formatting will move with the row data, when the rows are sorted/filtered by the user. So, what starts out as "first" and "last" may change.


    References: