Kamaloka
Kamaloka

Reputation: 139

Reducing width when collapsing a box

I'm trying to collapse a box not only by reducing its height (default behavior) but also its width, so that the other box gets the extra space; a bit like a collapsible sidebar. How to achieve that?

In the below example, I'd like box 2 to be minimized, and box 1 to get the extra width freed by box 2:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(

    column(width = 12,
           box(width = 9, "box 1"),
           box(width = 3, "box 2", collapsible = T),
    )
))

server <- function(input, output) {

}

shinyApp(ui, server)

Upvotes: 0

Views: 53

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84649

Here is a JavaScript way, which could be improved to handle more situations.

library(shiny)
library(shinydashboard)

sideBySideBoxes <- function(box1, box2) {
  tags$div(
    class = "row sbsboxes",
    box1, box2
  )
}

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    tags$head(
      tags$script(src = "sbsboxes.js")
    ),
    sideBySideBoxes(
      box(width = 9, "box 1"),
      box(width = 3, "box 2", collapsible = TRUE)
    )
  )
)

server <- function(input, output) {
  
}

shinyApp(ui, server)

Put the following JavaScript code in a file in the www subfolder of the app, name it sbsboxes.js.

$(document).ready(function() {
  $(".sbsboxes").each(function() {
    var $div = $(this);
    var $children = $div.children();
    var $child1 = $($children.get(0));
    var $child2 = $($children.get(1));
    var sm1 = $child1.attr("class");
    var sm2 = $child2.attr("class");
    var width1 = sm1[7];
    var width2 = sm2[7];
    var $box1 = $child1.find(".box");
    var $box2 = $child2.find(".box");
    $box2.on("hidden.bs.collapse", function() {
      $child2.removeClass(sm2).addClass("col-sm-1");
      $child1.removeClass(sm1).addClass("col-sm-11");
    });
    $box2.on("shown.bs.collapse", function() {
      $child2.removeClass("col-sm-1").addClass(sm2);
      $child1.removeClass("col-sm-11").addClass(sm1);
    });
  });
});

Upvotes: 0

Related Questions