Search code examples
rshinytooltipshinybs

Math mode in bsTooltip in shiny


I'm wondering whether these is any option to include math mode in tooltip title using bsTooltip() from shinyBS package.

Small example:

rm(list = ls())
library(shiny)
library(shinyBS)

ui <- basicPage(
  headerPanel("Tooltip test"),
  bsTooltip(id = "Equation", title = "\\(\\bar{X} = \\frac{1}{n}\\sum_{p = 1}^{n}X_p\\)", placement = "bottom", trigger = "hover", options = NULL),
  mainPanel(
    p("some text", htmlOutput("Equation", inline = TRUE))
  )
)

server <- shinyServer(function(input, output,session) {
  output$Equation <- renderUI({HTML("<font color='blue'><u>something which needs equation</u></font>")})
})
shinyApp(ui = ui, server = server)

The result (math mode) is not satisfactory:


Solution

  • No way with 'shinyBS'.

    Here is a way using the qTip2 JavaScript library.

    In order to use it, you have to download the files jquery.qtip.min.css and jquery.qtip.min.js, and put these two files in the www subfolder of the Shiny app.

    enter image description here

    library(shiny)
    
    js <- "
        $(document).ready(function() {
          $('#Equation').qtip({
            overwrite: true,
            content: {
              text: $('#tooltip')
            },
            position: {
              my: 'top left',
              at: 'bottom right'
            },
            show: {
              ready: false
            },
            hide: {
              event: 'unfocus'
            },
            style: {
              classes: 'qtip-youtube qtip-rounded'
            },
            events: {
              blur: function(event, api) {
                api.elements.tooltip.hide();
              }
            }
          });
        });
    "
    
    library(shiny)
    
    ui <- basicPage(
      tags$head(
        tags$link(rel = "stylesheet", href = "jquery.qtip.min.css"),
        tags$script(src = "jquery.qtip.min.js"),
        tags$script(HTML(js)),
      ),
      withMathJax(),
      headerPanel("Tooltip test"),
    
      mainPanel(
        p("some text", htmlOutput("Equation", inline = TRUE)),
        div(
          id = "tooltip", style = "display: none;",
          HTML("$$\\int_0^1 f(x) dx = \\pi$$")
        )
      )
    )
    
    server <- shinyServer(function(input, output,session) {
    
      output$Equation <- 
        renderUI({HTML("<font color='blue'><u>something which needs equation</u></font>")})
    
    })
    
    shinyApp(ui = ui, server = server)