samedi 17 février 2018

Randomly placed div's at page load

For a personal project I'm trying to fill the window with randomly generated div's. I got started with a code I found in some thread and tweaked it to my liking (color and width of the div's for example).

However, this code was designed to generate a div, then make it fade out, and cycle that again. What I'd like is to have a set number of div's loaded on page load and without them disappearing.

I do recognize the ".fadeOut" and ".remove()" at the end of the code, but for the life of me I can't figure out how to prevent the div's from disappearing without breaking the code, let alone having a set number of randomly placed div's appear at once.

(function makeDiv() {
  var divsize = ((Math.random() * 100) + 30).toFixed();
  var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
  $newdiv = $('<div/>').css({
    'width': 2 + 'px',
    'height': divsize + 'px',
    'border': '1px solid' + color,
    'transform': 'rotate(' + divsize + 'deg)',
    'background-color': color,
  });

  var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
  var posy = (Math.random() * ($(document).height() - divsize)).toFixed();

  $newdiv.css({
    'position': 'absolute',
    'left': posx + 'px',
    'top': posy + 'px',
    'display': 'none',
    'border-radius': '100px',
  }).appendTo('body').fadeIn(100).delay(300).fadeOut(200, function() {
    $(this).remove();
    makeDiv();
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



Aucun commentaire:

Enregistrer un commentaire