Fire a Javascript event handler on image click

Viewed 67

I want to fire a JS event handler when I click on an image in Shiny. The handler uses shiny:inputchanged (see here) and works for buttons. imageOutput probably is no input, so how can I create an event when I click on it?

library(shiny)

ui <- fluidPage(
  tags$script(HTML(
    "$(document).on('shiny:inputchanged', function(event) {  alert(event.name);})"
  )),
  titlePanel("Click on image or button"),
  fluidPage(
    mainPanel(
      actionButton("doit", "Click to check"), # Works!
      imageOutput("myimage", click = "image_click") # No response on click
    )
  )
)

server <- function(input, output, session) {
  output$myimage <- renderImage({
    list(src = system.file("help/figures/logo.png", package = "shiny"),
         width = 800, height = 800) 
  },
  deleteFile = FALSE
  )
}

shinyApp(ui = ui, server = server)
1 Answers

You can use the onclick() function from the shinyjs package:

library(shiny)
library(shinyjs)

ui <- fluidPage(
  tags$script(HTML(
    "$(document).on('shiny:inputchanged', function(event) {  alert(event.name);})"
  )),
  titlePanel("Click on image or button"),
  fluidPage(
    mainPanel(
      useShinyjs(),
      actionButton("doit", "Click to check"), # Works!
      imageOutput("myimage")
    )
  )
)

server <- function(input, output, session) {
  onclick("myimage", function(event) { alert(event) })
  output$myimage <- renderImage({
    list(src = system.file("help/figures/logo.png", package = "shiny"),
         width = 800, height = 800) 
  },
  deleteFile = FALSE
  )
}

shinyApp(ui = ui, server = server)
Related