6

Here is a working example of my best attempt to get table click event:

library(shiny)
library(DT)

runApp(shinyApp(
  ui = fluidPage(DT::dataTableOutput('table')),
  server = function(input, output, session) {
    output$table <- DT::renderDataTable({
      dt <- data.frame(a = 1)
      datatable(dt, rownames = FALSE, selection = 'none')
    })
    observeEvent(input$table_cell_clicked, {
      print(Sys.time())
    })}
))

The problem is that observeEvent reacts only if user clicks on the cell which differs from previously clicked. Is there a way to get event on any table click?

1
  • Since the output is ultimately a div on the webpage, I imagine you can use Javascript to catch a div click event. Mar 21, 2016 at 14:57

1 Answer 1

9

I think it s may be helpful

Try add callback with Shiny.onInputChange and add smth which changed all time ( rnd)

smt like

   JS("table.on('click.dt', 'td', function() {
            var row_=table.cell(this).index().row;
            var col=table.cell(this).index().column;
            var rnd= Math.random();
            var data = [row_, col, rnd];
           Shiny.onInputChange('rows',data );
    });")

and then use it like :

library(shiny)
library(DT)
runApp(shinyApp(
  ui = fluidPage(DT::dataTableOutput('table')),
  server = function(input, output, session) {
    output$table <- DT::renderDataTable({
      datatable(data.frame(a = c(1,2),b=c(2,3)), rownames = FALSE, selection = 'none', callback = JS("table.on('click.dt', 'td', function() {
            var row_=table.cell(this).index().row;
            var col=table.cell(this).index().column;
            var rnd= Math.random();
            var data = [row_, col, rnd];
           Shiny.onInputChange('rows',data );
    });")
      )}
    )

    observeEvent(input$rows, {
      print(input$rows)
      print(Sys.time())

    })}
))

Then parse all row and col from input$rows

PS. in datatables index start from 0 .

1
  • 2
    If your table is on several pages, input$rows[1] will refer to the row of the current page. To get the absolute row number in observeEvent use input$table_rows_current[input$rows[1]+1], see rstudio.github.io/DT/shiny.html
    – Valentas
    Apr 10, 2017 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.