Using Shiny.onInputChange() to detect a click

Say I have an object in the browser DOM with class="row" and id="row22".

I want to use Shiny.onInputChange() to detect a click on that object and send the id to a Shiny input$ variable. I've worn out Google looking for an example of how to do this but haven't come up with anything. Could someone who knows how to do this provide some sample code?

Thanks. - Tom

I would be interested in knowing too! It would be really useful to have a minimal reproducible example of your code and what you are trying to achieve.

Depending on your exact usecase, the shinyjs package has an onclick function that may work for you. It lets you run code (and gives you information about the click event) when an element is clicked. The main limitation that may not make it work for you is that you need to supply it with an ID, which means essentially you need to "pre register" whatever html elements you want to detect clicks on

Call me slow, but I just discovered that HTML 4 and 5 support onclick events on objects. So on the row of a table you can add this to the <tr> tag:

<tr onclick="my_row(nnn)">

where nnn is the row number.

In your Javascript you add a function that looks like this:

function my_row(n) {
   Shiny.onInputChange("js.row", n);

In your Shiny code you add an observer that looks for changes on input$js.row:

observeEvent(input$js.row, {
   print(paste0("Value of js.row is ", input$js.row))

That seems to work.


1 Like

Update: Since my last reply on this topic I've read a Javascript/Jquery book and am no longer using the HTML onclick attribute, which is considered very old school.

Instead I load a tiny bit of Javascript code that tells the browser to watch for clicks on buttons <button....> or anchors <a....> that don't have hrefs but do have ids, and then send me the id of the object that was clicked via Shiny.onInputChange().

This allows me to have one observeEvent() that handles all button and menu clicks. Details are here: Adding anchors to our Shiny button observer.