I'd like to hide an element when a shiny app starts, but unlike this example, the element to be hidden is part of a larger element which is visible.
In this example, the element to be hidden at the start is the drawing control which is part of a leaflet map. There is a button which toggles the visibility of the drawing control - how can I have it start with the drawing control hidden? The full code for the app follows below.
library(rbgm)
library(leaflet)
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
leafletOutput("mymap"),
actionBttn("toggle_button", "Toggle drawing")
)
server <- function(input, output, session) {
output$mymap <- renderLeaflet({
set.seed(2)
fs <- sample(bgmfiles::bgmfiles(), 1)
model <- boxSpatial(bgmfile(fs))
model <- spTransform(model, "+init=epsg:4326")
m <- leaflet() %>% addTiles()
m <- m %>% addPolygons(data = model, group = 'model') %>%
addDrawToolbar(targetGroup = 'model',
editOptions = editToolbarOptions(
selectedPathOptions = selectedPathOptions()))
m
})
observe({
shinyjs::hide(selector = "div.leaflet-draw") # <---- this doesn't hide the draw controls at the start!!
})
observeEvent(input$toggle_button, {
shinyjs::toggle(selector = "div.leaflet-draw")
})
}
shinyApp(ui, server)
I've tried using observe
to hide the element at the start however it doesn't do anything, presumably because the drawing control element loads after the observe event fires.
You can do
shinyjs::delay(0, shinyjs::hide(selector = "div.leaflet-draw"))
(without observer).
Another solution:
js <- "
$(document).on('shiny:value', function(e){
if(e.name === 'mymap'){
setTimeout(function(){$('div.leaflet-draw').hide();}, 0);
}
});
"
ui <- fluidPage(
useShinyjs(),
tags$head(tags$script(js)),
leafletOutput("mymap"),
...