Juicy Juicy - 2 months ago 6
Javascript Question

Dynamically changing columns sizes on click

I would like to have three columns on my page, but column2 should initially have a size of column size of 0, ie

col-md-0
. When the user clicks on a link in the navigation bar, I would like column2 to expand to
col-md-3
, and column3 should shrink to adjust.

For example, this is what I would imagine my columns'
html
to be when the page is loaded:

<div class="container-fluid">
<div class="row no-gutter">
<div id="col1" class="col-md-1">
<vs-navbar></vs-navbar>
</div>
<div id="col2" class="col-md-0">
<router-outlet></router-outlet>
</div>
<div id="col3" class="col-md-11">
<div class="placeholder">
</div>
</div>
</div>
</div>


The
navbar
could be:

<nav class="navbar navbar-inverse navbar-full">
<ul class="nav nav-stacked">
<li>
<a>Home</a>
</li>
<li>
<a>Info</a>
</li>
</ul>
</nav>


When the
Info
link is clicked, I would like the
html
to transition to:

<div class="container-fluid">
<div class="row no-gutter">
<div id="col1" class="col-md-1">
<vs-navbar></vs-navbar>
</div>
<div id="col2" class="col-md-3">
<router-outlet></router-outlet>
</div>
<div id="col3" class="col-md-8">
<div class="placeholder">
</div>
</div>
</div>
</div>


I have a vague but messy idea how this could be done with some javascript, but I've seen this kind of thing on several sites so I'm looking for the clean, recommended way of doing this, especially as I'm using bootstrap.

Answer

Because you have IDs, I assume you now the exact structure of your row.

If it is so, a solution can be based on toggleClass:

$('a:contains("Info")').on('click', function(e) {
  $('#col2').toggleClass('col-md-0 col-md-3')
  $('#col3').toggleClass('col-md-11 col-md-8')
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav class="navbar navbar-inverse navbar-full">
    <ul class="nav nav-stacked">
        <li>
            <a>Home</a>
        </li>
        <li>
            <a>Info</a>
        </li>
    </ul>
</nav>

<div class="container-fluid">
    <div class="row no-gutter">
        <div id="col1" class="col-md-1">
            <vs-navbar>aaaaaa</vs-navbar>
        </div>
        <div id="col2" class="col-md-0">
            <router-outlet>bbbbbb</router-outlet>
        </div>
        <div id="col3" class="col-md-11">
            <div class="placeholder">cccc
            </div>
        </div>
    </div>
</div>