Reputation: 513
How do I add a tooltip (or a mouseover popup) to cells of a datatable, that pulls data from another column?
For example if I display first three columns of mtcars in a datable, how do I display a tooltip with hp (horsepower) data of the car name I am currently hovering over with my mouse?
There are similar questions on how you can display static text as a tooltip, but I can't find a way to display data from another column as a toolptip.
#ui.R
library(shiny)
library(DT)
shinyUI(
mainPanel(
DT::dataTableOutput("tbl")
)
)
#server.R
library(shiny)
library(DT)
shinyServer(function(input, output,session) {
output$tbl = DT::renderDataTable(
datatable(mtcars[, 1:3]))
})
Upvotes: 1
Views: 843
Reputation: 7694
To get the tooltip with hp you can modify your server code as follows:
shinyServer(function(input, output,session) {
output$tbl <- DT::renderDataTable({
datatable(mtcars[, 1:4], options = list(rowCallback = JS(
"function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {",
"var full_text = aData[4]",
"$('td:eq(0)', nRow).attr('title', full_text);",
"$('td:eq(1)', nRow).attr('title', full_text);",
"$('td:eq(2)', nRow).attr('title', full_text);",
"$('td:eq(3)', nRow).attr('title', full_text);",
"}"),
columnDefs = list(list(visible=FALSE, targets=c(4)))
)
)
})
})
The JS
code adds the tooltip to first four columns with the value of hp column.
Here the dataset contains the hp column but we are hiding that column using columnDefs
parameter.
Hope it helps!
Upvotes: 2