Creating Responsive Equal Height Blocks with Vanilla JavaScript

Category: Javascript , Layout | November 20, 2014
Author: gabssnake
Views Total: 3,205
Official Page: Go to website
Last Update: November 20, 2014
License: MIT

Preview:

Creating Responsive Equal Height Blocks with Vanilla JavaScript

Description:

A minimalist way to create columns with equal height that works with multiple rows and responsive design. Written in vanilla JavaScript.

How to use it:

Add the following JavaScript snippet into your document. It will set the height of each article element in your body section to the height of the highest article element.

function sameHeights () {

  var nodeList = document.getElementsByTagName('article');
  var elems = [].slice.call(nodeList);

  var tallest = Math.max.apply(Math, elems.map(function(elem, index) {
    elem.style.minHeight = ''; // clean first
    return elem.offsetHeight;
  }));

  elems.forEach(function(elem, index, arr){ 
    elem.style.minHeight = tallest + 'px';
  });
  
}

var resized = true;
var timeout = null;

var refresh = function(){
  if(resized) {
    requestAnimationFrame(sameHeights);
  }
	clearTimeout(timeout);
	timeout = setTimeout( refresh, 100);
  resized = false;
};

window.addEventListener('resize', function() { resized = true; });

refresh();

It also comes with a jQuery solution to implement the equal height feature on your existing elements. Just include the following JavaScript snippet after the jQuery library.

function sameHeights () {
  var elems = $('article');
  elems.css('min-height', Math.max.apply(Math, elems.map(function() { 
    return $(this).height();
  }).get() ));
}

$('window').on('resize', function() { resized = true; });

refresh();

You Might Be Interested In:


Leave a Reply