Hi,
I am fairly new to shiny and I'm stuck on a problem concerning css classes of an html element (row) in a datatable.
What I want shiny to do, is to highlight a row in a datatable when hovering over the corresponding element in a plotly graph. I can do this with dataTableProxy and selectRows as in the example below, however I need the "selected" class for something else. So ideally I would like the row in my datatable to have the class "hover" when hovering over the corresponding bar in my plortly graph, just as it has the class "hover", when hovering over the actual row in the datatable. I tried shinyjs:: addClass and removeClass, but that doesn't seem to work. One problem is, that I cannot identify the id of my row to highlight.
library(DT)
library(plotly)
library(shinyjs)
library(shiny)
shinyApp(
ui = fluidPage(
tags$head(tags$style(HTML
("#table tr:hover {
background-color: rgba(240, 136, 33, 0.4) !important;
}"))),
fluidRow(
plotlyOutput(outputId = "ranking_plot"),
dataTableOutput(outputId = "table")
)
),
#### server ####
server = function(input, output, session) {
## plot ##
output$ranking_plot <- renderPlotly({
mtcars %>%
plot_ly(source = "ranking", x = row.names(mtcars), y = ~mpg, type = 'bar') %>%
layout(xaxis= list(title=FALSE, showticklabels = TRUE, categoryorder="total descending"),
yaxis= list(showticklabels = TRUE))
})
## table ##
output$table <- renderDataTable({
DT_Out <- datatable (mtcars, rownames=TRUE, selection="single", class="display"
,callback = JS("
table.on('mouseover', 'td', function() {
$(this).parent().addClass('hover')
});
table.on('mouseout', 'td', function() {
$(this).parent().removeClass('hover')
});
return table;
")
)
})
## tableProxy ##
table_proxy = dataTableProxy('table')
selected_car_plotly_hover <- reactive({
if (is.null(event_data("plotly_hover", source = "ranking")))
return(NULL)
event_data("plotly_hover", source = "ranking")})
observe({
selectRows(table_proxy, selected=(selected_car_plotly_hover()[[2]]+1))
})
}
)
Can anybody help?