multiple javascript functions in rshiny

How do you have multiple javascript functions in RShiny? I'm combining example 1 and 2 from this example extendShinyjs: Extend shinyjs by calling your own JavaScript functions

jsCode <- '
    shinyjs.backgroundCol = function(params) {
      var defaultParams = {
        id : null,
        col : "red"
      };
      params = shinyjs.getParams(params, defaultParams);

      var el = $("#" + params.id);
      el.css("background-color", params.col);
    }'
jsCode <- "shinyjs.pageCol = function(params){$('body').css('background', params);}"
shinyApp(
  ui = fluidPage(
    useShinyjs(),
    extendShinyjs(text = jsCode, functions = c("backgroundCol")),
    extendShinyjs(text = jsCode, functions = c("pageCol")),
    selectInput("col", "Colour:",
                c("white", "yellow", "red", "blue", "purple"))
    p(id = "name", "My name is Dean"),
    p(id = "sport", "I like soccer"),
    selectInput("col", "Colour",
                c("green", "yellow", "red", "blue", "white")),
    selectInput("selector", "Element", c("sport", "name", "button")),
    actionButton("button", "Go")
  ),
  server = function(input, output) {
    observeEvent(input$button, {
      js$backgroundCol(input$selector, input$col)
    })
    observeEvent(input$col, {
      js$pageCol(input$col)
    })
  }
)

In your above code you are overwriting your first variable jsCode with the second one.
Just put both js functions in the same string.

Furthermore all shiny inputs need their unique id. You used "col" twice.

Please check the following:

library(shiny)
library(shinyjs)


jsCode <- '
    shinyjs.backgroundCol = function(params) {
      var defaultParams = {
        id : null,
        col : "red"
      };
      params = shinyjs.getParams(params, defaultParams);
      var el = $("#" + params.id);
      el.css("background-color", params.col);};
    shinyjs.pageCol = function(params){$("body").css("background", params);};'

shinyApp(
  ui = fluidPage(
    useShinyjs(),
    extendShinyjs(text = jsCode, functions = c("backgroundCol", "pageCol")),
    selectInput("pageCol", "Page colour",
                c("green", "yellow", "red", "blue", "white")),
    hr(),
    selectInput("selector", "Element", c("sport", "name", "button")),
    selectInput("backgroundColSelect", "Background colour:",
                c("yellow", "white", "red", "blue", "purple")),
    p(id = "name", "My name is Dean"),
    p(id = "sport", "I like soccer"),
    actionButton("button", "Go")
  ),
  server = function(input, output) {
    observeEvent(input$button, {
      js$backgroundCol(input$selector, input$backgroundColSelect)
      js$pageCol(input$pageCol)
    })
  }
)

Thank you! That worked.

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.