MrQwest

Random box heights with jQuery

On a recent project that I’ve been building, the client requested that the index layout featured a pinterest style layout. The obvious answer being MasonryJS. Now normally, that’d be just perfect if the main index content was images as I’d be able to use the image heights as element heights.

However, this index page didn’t have images, just 12+ post containers with random heights to give the pinterest look.

I decided to use jQuery to add random heights to each post container using the following code:

$(function() {
  $(".element").each(function(){
    var homeHeightMin = 200;
    var homeHeightMax = 350;
    var randHeight = Math.floor(Math.random() * (homeHeightMax - homeHeightMin + 1)) + homeHeightMin;
    $(this).css('height',randHeight);
  });
});

The homeHeightMin and homeHeightMax set min & max limits to the container. In this instance, it’s minimum height is 200px and maximum is 350px.

randHeight does all the magic. By default, Math.random() grabs a random number between 0 & 1; not only that though, the random number has 16 decimal places. That’s not much help if we want our element to be between 200 & 350. So we use Math.floor() to round that number down.

Obviously if Math.random() gave us a value of 0.5888178590685129, rounding that down to the nearest whole number would give us a value of 0. Equally not helpful.

So before we run Math.floor(), we need to run a sum that’ll get us a useable value. The (homeHeightMax - homeHeightMin + 1) sum gives us the maximum value between our min & max values. In this case, it’s 151.

0.5888178590685129 * 151 outputs 88.911496719 still not within our min & max values so we add our minimum value to this output giving us 288.911496719

We now wrap that sum with Math.Floor() to round it down giving us our random value of 288.

Now back to the original function, we use $(this).css('height',randHeight'); to set the height of our container element to 288px.

Using the jQuery .each() function allows us to apply our random heights to every element we specify in our original jQuery selector.

And there we have it, a pinterest style layout using jQuery to produce random heights for each container element. Here’s a JSFiddle as an example.

As an aside, a few people on twitter did help me with this issue… but I can’t remember who, and the twitter search doesn’t go back that far! If you’re one of those special people, thank you!!!

Tags

Comments

Leave a comment