Kronkorken Kronkorken - 4 months ago 90
Javascript Question

Change column sizes by clicking - Bootstrap

I need your help again.

I want to change the column size by clicking a button.

Like from this:
enter image description here

To this:
enter image description here

With the following code(from stackoverflow) it's possible to change one colummn size. I want to change at least two.

HTML

<div class="col-md-2">
<span class="glyphicon glyphicon-menu-hamburger"></span>
Some content
</div>


JS

$('.glyphicon-menu-hamburger').click(function() {
$(this)
// Find parent with the class that starts with "col-md"
// Change class to "col-md-3"
.closest('[class^="col-md"]')
.toggleClass('col-md-2 col-md-1')
// Find siblings of parent with similar class criteria
// - if all siblings are the same, you can use ".siblings()"
// Change class to "col-md-2"
.siblings('[class^="col-md"]')
.removeClass('col-md-1')
.addClass('col-md-2');});


Thanks!

Answer

Check this:

$("button").click(function(){
  var columns_container = $(".dynamic-columns");
  if (!columns_container.hasClass("expanded")) {
    $(".dynamic-columns .col:first").removeClass("col-xs-2");
    $(".dynamic-columns .col:first").addClass("col-xs-1");
    
    $(".dynamic-columns .col:last-child").removeClass("col-xs-8");
    $(".dynamic-columns .col:last-child").addClass("col-xs-9");
    columns_container.toggleClass("expanded");
  }
  else {
    $(".dynamic-columns .col:first").removeClass("col-xs-1");
    $(".dynamic-columns .col:first").addClass("col-xs-2");
    
    $(".dynamic-columns .col:last-child").removeClass("col-xs-9");
    $(".dynamic-columns .col:last-child").addClass("col-xs-8");
    columns_container.toggleClass("expanded");
  }
});
button {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 10;
}

h4 {
  text-align: center;  
}

.main-container {
  margin-top: 50px; 
}

.col {
  background-color: #ccc;
}
<html>
  <head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">    </script>
  </head>
  <body>
    <div class="container-fluid main-container">
      <div class="row dynamic-columns">
        <button>Toggle</button>
        <div class="col-xs-2 col">
          <h4>First Column</h4>
        </div>
        <div class="col-xs-2 col">
          <h4>Second Column</h4>
        </div>
        <div class="col-xs-8 col">
          <h4>Third column</h4>
        </div>
      </div>
    </div>
  </body>
</html>

Comments