Implementing Shiny with shinyjs
In order to utilize a JavaScript function in R using shinyjs, the function name must be prefixed by shinyjs.
. This allows it to be recognized by the functions
parameter of shinyjs::extendShinyjs()
and called in R through js$MySelection()
.
A specific approach I've employed is
shiny::onFlushed(function() { js$MySelection() })
"onFlushed registers a function that will be called after Shiny flushes the reactive system."
custom.js
:
shinyjs.MySelection=function() {
let links = document.querySelectorAll(".link-section a");
console.log(links);
}
app.R
:
library(shiny)
library(shinyjs)
ui =fluidPage(
div(
useShinyjs(),
shinyjs::extendShinyjs(
script = "custom.js", # without www
functions = c("MySelection")
),
navbarPage(
title = "Test",
id = "test",
selected = "One",
tabPanel(title = "One",
div("some links", style = "margin-top: 6rem;"),
div(uiOutput(outputId = "test_ui"))
)
)
)
)
server = function(input, output, session){
output$test_ui = renderUI({
tagList(
div(class = "link-section",
tags$a("link_one"),
tags$a("link_two"),
tags$a("link_three")
# in case of more delayed events or interactions :
# , shinyjs::hidden( textInput("hiddenInput","hiddenlabel"))
),
)
})
# in case of more delayed events or interactions :
# observeEvent(input$hiddenInput,{
# js$MySelection()
# })
shiny::onFlushed(
function() {
js$MySelection()
}
)
}
shinyApp(ui = ui, server = server)
Utilizing Pure Shiny without shinyjs
- Call javascript function on page load in R shiny
custom.js
:
$(document ).on("shiny:sessioninitialized", function(event) {
MySelection=function() {
let links = document.querySelectorAll(".link-section a");
console.log(links);
}
})
app.R
:
library(shiny)
ui =fluidPage(
div(
tags$head(tags$script(type="text/javascript",src="custom.js")),
navbarPage(
title = "Test",
id = "test",
selected = "One",
tabPanel(title = "One",
div("some links", style = "margin-top: 6rem;"),
div(uiOutput(outputId = "test_ui"))
)
)
)
)
server = function(input, output, session){
output$test_ui = renderUI({
tagList(
div(class = "link-section",
tags$a("link_one"),
tags$a("link_two"),
tags$a("link_three")
),
tags$script(type="text/javascript", "MySelection()")
)
})
}
shinyApp(ui = ui, server = server)