Search code examples
jqueryrtwitter-bootstrapshinytooltip

In R Shiny, how do you make a tooltip appear on click instead of on hover?


I'm making a tooltip in R shiny attached to an "info" icon like so:

library(shiny)
ui <- fluidPage(
  span(
    `data-toggle` = "tooltip", 
    `data-placement` = "auto",
    title = "I'm a tooltip!",
    icon("info-circle", 
         style="font-size: 150%;"))
)

server <- function(input, output) {}
shinyApp(ui = ui, server = server)

This tooltip appears upon hovering over the icon. However, my App would ideally work on mobile too, where hover isn't a thing. How can I make it appear upon click too/instead (or some other mobile-friendly option)?


Solution

  • I did a bit more digging and it looks like I was really close. Here's what worked:

    library(shiny)
    ui <- fluidPage(
      span(
        `data-toggle` = "tooltip",
        `data-placement` = "auto",
        `data-trigger` = "click hover",
        title = "I'm a tooltip!",
        icon("info-circle", style="font-size: 150%;")),
    
      tags$script(
        HTML(
          "$(function () { 
            $('[data-toggle=tooltip]').tooltip();   
          });"
        )
      )
    )
    
    server <- function(input, output) {}
    shinyApp(ui = ui, server = server)
    

    All I did is add in the JavaScript portion in the center, where I (presumably) activate the tooltip method on any elements which have their data-toggle attributes set to tooltip. I then also added in a data-trigger attribute to my span that specifies both click and hover as triggers (see here for useful documentation). That way, it appears on hover and disappears when the mouse moves off, but it also opens and stays open upon click, which should enable useful functionality on both desktop and mobile.

    Incidentally, I also found out that something similar can be accomplished by using the rel attribute instead, but this is considered bad practice (see here for details). You can also make these tooltips into popovers by enabling the popover method instead (see here for some relevant code). Popovers appear more complex but also maybe a bit fancier and more customizable.