Clemsang
Clemsang

Reputation: 5481

R Shiny tooltip for pickerInput shiny js

I am trying to add a tooltip to select input content. I would like to have the txt vector as a tooltip corresponding to the input on hover.

Javascript code is not fontionnal but here is my draft:

library(shiny)
library(shinyjs)
library(shinyWidgets)

if (interactive()) {

  ui <- fluidPage(
    useShinyjs(),
    extendShinyjs(text = '
      shinyjs.selectInput_tooltips = function(id, tooltips){
        var selectiInput = $("#"+id).closest("div").find(".dropdown-menu").get(0);
        var element_selectInput = selectiInput.childNodes;
        for(var i = 0; i< element_selectInput.length; i++){
          element_selectInput[i].title = tooltips[i];
        }
      }; 
    '),
    uiOutput("picker")

  )
  server <- function(input, output) {
    output$picker <- renderUI({
      txt <- c("Explanation 1", "Explanation 2", "Explanation 3")
      tagList(
        pickerInput(inputId = "id", label = "Value :", choices = c("num1" = 1, "num2" = 2, "num3" = 3)),
        js$selectInput_tooltips("id", txt)
      )
    })
  }
  shinyApp(ui, server)
}

Any other way to do it might be accepted and any help is greatly appreciated.

Thank you very much.

Upvotes: 0

Views: 1045

Answers (1)

Sylvain Berthelot
Sylvain Berthelot

Reputation: 141

You can see third example of extendShinyjs to use function with several arguments !

library(shiny)
library(shinyjs)
library(shinyWidgets)

txt <- c("Explanation 1", "Explanation 2", "Explanation 3")
ui <- fluidPage(
  useShinyjs(),
  extendShinyjs(text = '
          shinyjs.selectInput_tooltips = function(params){

          var defaultParams = {
            id : null,
            tooltips : null
          };
          params = shinyjs.getParams(params, defaultParams);

          var selectInput = $("#"+params.id).closest("div").find(".dropdown-menu").get(1);
          var element_selectInput = selectInput.childNodes;

          if(element_selectInput.length >0 && element_selectInput[0].title == ""){ // to be trigger only once
            for(var i = 0; i< element_selectInput.length; i++){
              element_selectInput[i].title = params.tooltips[i];
            }
          }

        }; 
      '),
  pickerInput(inputId = "id", label = "Value :", choices = c("num1" = 1, "num2" = 2, "num3" = 3))

)
server <- function(input, output) {
  # throw your function when you click on pickerInput
  # Use this because if you don't click on it, the function couldn't work !
  # because choices of pickerInput doesn't exist yet
  onclick("id" ,js$selectInput_tooltips("id",txt)) 
}
shinyApp(ui, server)

Upvotes: 1

Related Questions