The main idea behind this code snippet is that upon triggering a .click()
event, the following actions are taken:
- All classes starting with
col-lg-*
are removed based on the number of columns with the class .hidden
.
- The visibility of the first or last column is toggled by adding or removing the
.hidden
class.
- The appropriate
col-lg-*
class is added based on the count of columns with the class .hidden
.
HTML
<p>
<button class="btn btn-info toggle-item toggle-first">Toggle first column</button>
<button class="btn btn-info toggle-item toggle-last">Toggle last column</button>
</p>
<div class="row">
<div class="first column hidden">
first column
</div>
<div class="column col-lg-6">
second column
</div>
<div class="column col-lg-6">
third column
</div>
<div class="last column hidden">
fourth column
</div>
</div>
JavaScript
jQuery('.toggle-item').click(function() {
var count = jQuery('.column.hidden').length;
if (count === 2) {
jQuery('.column').removeClass('col-lg-6');
} else if (count === 1) {
jQuery('.column').removeClass('col-lg-4');
} else if (count === 0) {
jQuery('.column').removeClass('col-lg-3');
}
if (jQuery(this).hasClass('toggle-first')) {
jQuery('.column.first').toggleClass('hidden');
} else {
jQuery('.column.last').toggleClass('hidden');
}
count = jQuery('.column.hidden').length;
if (count === 2) {
jQuery('.column').addClass('col-lg-6');
} else if (count === 1) {
jQuery('.column').addClass('col-lg-4');
} else if (count === 0) {
jQuery('.column').addClass('col-lg-3');
}
});
For a live demonstration of this functionality, you can visit this demo link.