Dominic Dominic - 6 months ago 42
HTML Question

Detect number of columns in a bootstrap grid with javascript

I am using a javascript to set the height of divs to make sure that the each row of divs in a grid has the same height

The divs are each setup as:

<div class="col-xs-12 col-sm-6 col-md-4">


So that on different size devices they show as either 3 column, 2 column or a single column

My javascript is as follows:

function fitRows( $container, options ) {
var cols = options.numColumns,
$els = $container.children(),
maxH = 0, j,
doSize;

doSize = ( $container.width() != $els.outerWidth(true) );

$els.each(function( i, p ) {

var $p = $( p ), h;

$p.css( 'min-height', '' );
if ( !doSize ) return;

h = $p.outerHeight( true );
if ( i % 3 == cols - 1 ) {
for ( j=cols;j;j--) {
$p.css( 'min-height', maxH );
$p = $p.prev();
}
maxH = 0;
} else {

maxH = Math.max( h, maxH );
}

});
}

$(function() {

var opts = {
numColumns: 3
};

fitRows( $( '.tiles' ), opts );

$( window ).on( 'resize', function() {
fitRows( $( '.tiles' ), opts );
});
$( window ).on( 'load', function() {
fitRows( $( '.tiles' ), opts );
});
});


This works perfectly when either 3 columns or 1 column is shown. Is there anyway to detect when 2 columns are being display and change the javascript accordingly

Answer

In the end I went with an if statement based on the size of the window to workout the number of columns

if ($(window).width() >= 992 ){
    $columns = 3;
}
else if ($(window).width() >= 768 ){
    $columns = 2;
}       
else {
    $columns = 1;   
}                       
var opts = {    
    numColumns: $columns
};

and then replaced i % 3 with i % cols