Search code examples
rshinyshinyjs

activate tabpanel from another tabpanel


I want when i start the application the tab panel tab2 = desactivated, and will be activated once i click the button in the first tab panel tab1, i tried with shinyjs and through CSS properties but i can not do that.

thanks for your help Alex

library(shiny)
library(shinyjs)
runApp(list(
ui = bootstrapPage(
tabsetPanel(
  tabPanel(title = "tab1", id="tab1",
           br(),
           actionButton("click", label = "View tab2 panel")),
  tabPanel(title = "tab2", id="tab2")
)
),
server = function(input, output, session){
}
))

Solution

  • Some small clarifications on the arguments value, id, and value working from @DeanAttali's reprex:

    library("shiny")
    library("shinyjs")
    library("V8") ## Required for shinyjs::extendShinyjs()
    
    ## JavaScript that dis/enables the ABILITY to click the tab (without changing aesthetics)
    app_jscode <-
      "shinyjs.disableTab = function(name) {
        var tab = $('.nav li a[data-value=' + name + ']');
        tab.bind('click.tab', function(e) {
          e.preventDefault();
          return false;
        });
        tab.addClass('disabled');
      }
      shinyjs.enableTab = function(name) {
        var tab = $('.nav li a[data-value=' + name + ']');
        tab.unbind('click.tab');
        tab.removeClass('disabled');
      }"
    ## css snipit that makes it LOOK like we are/n't able click the tab (with outchanging functionality)
    app_css <-
      ".nav li a.disabled {
        background-color: #aaa !important;
        color: #333 !important;
        cursor: not-allowed !important;
        border-color: #aaa !important;
      }"
    
    ui = fluidPage(
      shinyjs::useShinyjs(),
      shinyjs::extendShinyjs(text = app_jscode),
      shinyjs::inlineCSS(app_css),
      navbarPage(title = "Navbar title!", id = "navbarid",
                 tabPanel(title = "tab1", ## id and value args not needed
                          br(),
                          p("in tab 1."),
                          actionButton("btn", label = "toggle locked tabs")),
                 tabPanel(title = "tab2", ## id and value args not needed
                          p("in tab 2."))
      )
    )
    server = function(input, output, session) {
      ## Disable tab2 on page load
      js$disableTab("tab2")
      
      observeEvent(input$btn, {
        ## Enable tab2 when clicking the button
        shinyjs::js$enableTab("tab2") ## On a tab's title
        ## Switch to tab2
        updateNavbarPage(session, "navbarid", "tab2") ## On navbar's id, tab's title
        #### Taking it further: 
        ## Also disable tab1 as a selection
        shinyjs::js$disableTab("tab1")
      })
    }
    shinyApp(ui = ui, server = server)