Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The first problem is that all widths and backgrounds will be set to be the same as the random numbers are only generated once. You need something like:</p> <pre><code>$('.footerbars span').each(function(i, e) { $(e).css('width', (Math.random() * 10) + '%') .css('background-color', 'rgba('58,130,255,' + ((Math.random() * 0.6) + 0.3) +')'); }); </code></pre> <p>The problem with this is that the widths may not all add up to 100%. To solve this we need to first generate the set of random numbers, then scale them so they add up to 100, and then apply them to the spans.</p> <pre><code>var numSpans = $('.footerbars span').length; var widths = []; var total = 0; for(var i = 0; i &lt; numSpans; i++) { widths[i] = Math.random()+1; // generate a new random width for this span - and make it definitely not zero total += widths[i]; // and update the total width so far; } // Now we know what the total random number is (something between numSpans and 2*numSpans) // we can scale these so the sum actually is 100 for(var i = 0; i &lt; numSpans; i++) widths[i] = Math.floor(widths[i] * (100 / total)); </code></pre> <p>Now <code>widths[i]</code> contains the % width of the ith span in .footerbars, so amend the second line of the first bit of code to be:</p> <pre><code>$(e).css('width', widths[i]) </code></pre> <p>Full code:</p> <pre><code>var numSpans = $('.footerbars span').length; var widths = []; var total = 0; for(var i = 0; i &lt; numSpans; i++) { widths[i] = Math.random()+1; // generate a new random width for this span - and make it definitely not zero total += widths[i]; // and update the total width so far; } // Now we know what the total random number is (something between numSpans and 2*numSpans) // we can scale these so the sum actually is 100 for(var i = 0; i &lt; numSpans; i++) widths[i] = Math.floor(widths[i] * (100 / total)); $('.footerbars span').each(function(i, e) { $(e).css('width', widths[i]) .css('background-color', 'rgba('58,130,255,' + ((Math.random() * 0.6) + 0.3) +')'); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload