neves
neves

Reputation: 846

Hide dropdown options on shinydashboard when click out

I would like to exit an option (menuSubItem) when I click outside of this field, but the option does not disappear when I click outside. I tried a solution with CSS, but it didn't work! My code:

library(shiny)
library(shinydashboard)

header <- dashboardHeader(title = "Dashboard", titleWidth = 320)

sidebar <- dashboardSidebar(
  width = 320,
  sidebarMenu(
    menuItem(
      text = "A1"
    ),
    menuItem(
      text = "A2",
      menuSubItem(
        text = "AA1"
      ),
      menuSubItem(
        text = "AA2"
      ), 
      menuSubItem(
        text = "AA3"
      )
    )
  )
)

body <- dashboardBody()

ui <- dashboardPage(header = header, sidebar, body)

server <- function(input, output) {
  
}

shinyApp(ui, server)

I would like to click outside of A2 and have it (A2) close the dropdown menu when this click is done.

I tried insert this code in body:

body <- dashboardBody(

  HTML(
  "<script>

  $(function() {

    $(document).on('click', function() {
      $('.skin-blue .treeview-menu>li>a').slideUp();
    });
 
  });

  </script>"
  )

)

But don't work.

Upvotes: 3

Views: 306

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33442

We can provide the menuItem with an id and remove the css class menu-open:

library(shiny)
library(shinydashboard)

header <- dashboardHeader(title = "Dashboard", titleWidth = 320)

sidebar <- dashboardSidebar(width = 320,
                            sidebarMenu(
                              menuItem(text = "A1"),
                              menuItem(
                                text = "A2",
                                id = "A2ID",
                                menuSubItem(text = "AA1"),
                                menuSubItem(text = "AA2"),
                                menuSubItem(text = "AA3")
                              )
                            ))

body <- dashboardBody(tags$script(
  HTML(
    "$(document).on('shiny:connected', function(event) {
        $(document).on('click', function(evt) {
          if($(evt.target).closest('#sidebarItemExpanded > ul > li.treeview').length)
            return;
          var el = document.getElementById('A2ID');
          el.style.display = 'none';
          el.classList.remove('menu-open');
      });
    });"
  )
))

ui <- dashboardPage(header = header, sidebar, body)

server <- function(input, output, session) {}

shinyApp(ui, server)

result

Some related links:

jQuery click anywhere in the page except on 1 div

https://github.com/rstudio/shinydashboard/issues/347

Upvotes: 7

Related Questions