Run R code when an event is triggered on an element

onclick runs an R expression (either a shinyjs function or any other code) when an element is clicked. onevent is similar, but can be used when any event is triggered on the element, not only a mouse click. See below for a list of possible event types. Using "click" results in the same behaviour as calling onclick.

onclick(id, expr, add = FALSE)

onevent(event, id, expr, add = FALSE)


The id of the element/Shiny tag


The R expression or function to run after the event is triggered. If a function with an argument is provided, it will be called with the JavaScript Event details as its argument. Using a function can be useful when you want to know for example what key was pressed on a "keypress" event.


If TRUE, then add expr to be executed after any other code that was previously set using onevent or onclick; otherwise expr will overwrite any previous expressions. Note that this parameter works well in web browsers but is buggy when using the RStudio Viewer.


The event that needs to be triggered to run the code. See below for a list of possible event types.


shinyjs must be initialized with a call to useShinyjs() in the app's ui.

Possible event types

Any mouse or keyboard events that are supported by JQuery can be used. The full list of events that can be used is: click, dblclick, hover, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, keydown, keypress, keyup.

See Also

useShinyjs, runExample

  • onevent
  • onclick
  • onevent
if (interactive()) {

    ui = fluidPage(
      useShinyjs(),  # Set up shinyjs
      p(id = "date", "Click me to see the date"),
      p(id = "coords", "Click me to see the mouse coordinates"),
      p(id = "disappear", "Move your mouse here to make the text below disappear"),
      p(id = "text", "Hello")
    server = function(input, output) {
      onclick("date", alert(date()))
      onclick("coords", function(event) { alert(event) })
      onevent("mouseenter", "disappear", hide("text"))
      onevent("mouseleave", "disappear", show("text"))
# }
  # The shinyjs function call in the above app can be replaced by
  # any of the following examples to produce similar Shiny apps
  onclick("disappear", toggle("text"))
  onclick(expr = text("date", date()), id = "date")
# }
Documentation reproduced from package shinyjs, version 1.0, License: AGPL-3

Community examples

Looks like there are no examples yet.