# NOT RUN {
# Example 1:
# Change the page background to a certain colour when a button is clicked.
jsCode <- "shinyjs.pageCol = function(params){$('body').css('background', params);}"
shinyApp(
ui = fluidPage(
useShinyjs(),
extendShinyjs(text = jsCode, functions = c("pageCol")),
selectInput("col", "Colour:",
c("white", "yellow", "red", "blue", "purple"))
),
server = function(input, output) {
observeEvent(input$col, {
js$pageCol(input$col)
})
}
)
# ==============
# Example 2:
# Change the background colour of an element, using "red" as default
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);
}'
shinyApp(
ui = fluidPage(
useShinyjs(),
extendShinyjs(text = jsCode, functions = c("backgroundCol")),
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)
})
}
)
# ==============
# Example 3:
# Create an `increment` function that increments the number inside an HTML
# tag (increment by 1 by default, with an optional parameter). Use a separate
# file instead of providing the JS code in a string.
# Create a JavaScript file "myfuncs.js" in a "www/" directory:
shinyjs.increment = function(params) {
var defaultParams = {
id : null,
num : 1
};
params = shinyjs.getParams(params, defaultParams);
var el = $("#" + params.id);
el.text(parseInt(el.text()) + params.num);
}
# And a shiny app that uses the custom function we just defined. Note how
# the arguments can be either passed as named or unnamed, and how default
# values are set if no value is given to a parameter.
library(shiny)
shinyApp(
ui = fluidPage(
useShinyjs(),
extendShinyjs("myfuncs.js", functions = c("increment")),
p(id = "number", 0),
actionButton("add", "js$increment('number')"),
actionButton("add5", "js$increment('number', 5)"),
actionButton("add10", "js$increment(num = 10, id = 'number')")
),
server = function(input, output) {
observeEvent(input$add, {
js$increment('number')
})
observeEvent(input$add5, {
js$increment('number', 5)
})
observeEvent(input$add10, {
js$increment(num = 10, id = 'number')
})
}
)
# }
Run the code above in your browser using DataLab