Shiny with shinyjs
The function name of js function is prefixed by shinyjs.
to be known by functions
parameter of shinyjs::extendShinyjs()
and called in R by js$MySelection()
.
I've used 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)
Pure Shiny without shinyjs
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)