Integrating google analytics and shiny

The example of integrating google analytics with Shiny here is confusing: https://shiny.rstudio.com/articles/google-analytics.html

The example said to use the following to create an event to record when the user interacted with the selectInput widget:

  $(document).on('change', 'select', function(e) {
    ga('send', 'event', 'widget', 'select data', $(e.currentTarget).val());
  });

But in the Shiny function, that widget is called "var", as follows:

  selectInput("var", "Display",
    choices = c(
      "Percent of time sunny" = "sun_percent",
      "Annual hours of sunshine" = "total_hours",
      "Annual clear days" = "clear_days"
    )
  )

So, where did "select data" come from in the jQuery and/or how does the ga function know to watch the "var" widget for change?

Google Analytics doesn't have any idea that it's running on a Shiny app. So instead, what this jQuery code is looking at is the final HTML code that's created when the Shiny app runs. In this case, the selectInput option in Shiny creates a HTML select tag - see the screenshot below:

By looking at that select tag and its value, the jQuery code is able to figure out what was selected even though it has no understanding of the underlying Shiny code. If you look at the example further, you can see the same thing for the button tag created by the actionButton code in Shiny as well.

We note this in the article:

Note: to write effective jQuery code, you will need to be able to uniquely identify the widgets that you wish to track. This may require you to explore the document structure of the finished app, for example in your browser’s developer tools console.

but it could probably be made more explicit what exactly we're doing there. I've passed this along to our team to see what we can do to update this article here.

It still seems like the jQuery function would need to be given the select tag's id ("var") instead of just that it's a <select> tag. I'll just have to learn more about it I suppose. Thanks!

@ian already gave a detailed response to this, so I just want to add that it's possible to watch only the "var" by passing only the element id to the function instead of the <select> tag, using:

  $(document).on('change', '#var', function(e) {
    ga('send', 'event', 'widget', 'select data', $(e.currentTarget).val());
  });
1 Like

Ah! Yes! Thank you. I tried this but didn't have the #. I think it would help to clarify this in the article.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.