Create an `increment` function that increments the number inside an HTML
tag (increment by 1 by default, with an optional parameter).
Create a JavaScript file "myfuncs.js":
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)
runApp(shinyApp(
ui = fluidPage(
useShinyjs(),
extendShinyjs("myfuncs.js"),
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,session) {
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