JSFiddle - React, Tailwind, and code Playground

by sammy

HTML

<button class='add'>add</button>
<button class='remove'>remove</button>
<input type='number' class='amount' value='1'>
<div class='imgs'>
    <div class='img'></div>
</div>
<div class='stats'></div>

CSS

body {
    font-family: arial;
    font-size: 15px;
}
.imgs {
    width: 530px;
    background: blue;
    overflow: hidden;
}
.img {
    background: lightgrey;
    float: left;
    border: 0px solid white;
    box-sizing: border-box;
    text-align: center;
    color: white;
    box-shadow: inset 0px 0px 10px grey;
}
.img:hover {
    opacity: .8;
}

JavaScript

/*
W: imgs width
H: imgs height
n: number of img elements
nW: base width of img elements for which to multiply by
*/
var Phi = Math.pow(5, .5) * .5 + .5,
    phi = 1 / Phi;

var W = $('.imgs').width();
var H = W * phi;

var n = $('.img').length;
var nW = W / fib(n + 1);

$('.imgs').css('maxHeight', H);

$('.img').each(algorithm);

$(window).on('mousemove', function (ev) {
    var stats = $(ev.target).data('stats');

    var actualH = $('.imgs').height(),
        actualW = $('.imgs').width();

    $('.stats').html(stats ||
        'nW:' + nW +
        '<br>W:' + W +
        '<br>H:' + H +
        '<br>actual-W:' + actualW +
        '<br>actual-H:' + actualH);
});

$('.add').click(function () {
    var a = ~~$('.amount').val();
    while (a--) {
        $('.imgs').append("<div class='img'></div>");
    }

    n = $('.img').length;
    nW = W / fib(n + 1);

    $('.img').each(algorithm);
});
$('.remove').click(function () {
    var a = ~~$('.amount').val();
    while (a--) {
	    $('.img').last().remove();
    }

    n = $('.img').length;
    nW = W / fib(n + 1);

    $('.img').each(algorithm);
});

function algorithm(i) {
    /*
  fibI: nth index in the fibonacci series
  f: fibonacci number
  w: width of img element
  prevW: previous img element's width (not used)
  sum: sum of prevW and w (not used)
  */
    var fibI = n - i;
    var $img = $(this);
    var f = fib(fibI);

    var w = f * nW;
    var prevW = fib(fibI + 1) * nW;
    var sum = prevW + w;

    $img.data('stats', 'fibI:' + fibI + '<br>f:' + f + '<br>w:' + w + '<br>prev-w:' + prevW + '<br>sum:' + sum)
        .outerWidth(w).outerHeight(w);
}


// Returns nth fibonacci number in the fibonacci series
function fib(n) {
    return Math.round(Math.pow(Phi, n) / Math.sqrt(5));
}