Symbios Symbios - 5 months ago 21
CSS Question

Create divs in random places

I wish to create a div and position it in random places on the screen every 2 seconds. How would I accomplish this using PHP or Javascript? I am ok with using things like CSS.
div:

var blueMass = document.createElement('div');
blueMass.style.position = "absolute";
blueMass.innerHTML = "<img src='./pic/bluemass.png' height='35' width='35' />";
blueMass.id = "bluemass";
blueMass.className = "bluemass";

// my timer
window.setInterval(function(){
// Create the divs in here
}, 3000);


<div class="bluemass" id="bluemass">
<img src='./pic/bluemass.png' height='35' width='35' />
</div>

Answer

// no jQuery
$=document.querySelector.bind(document); // create selector
setInterval(function(){
  s=$('div').style;
  s.top=Math.random()*window.innerWidth+'px'; // multiply random (0..1) value by window height (you may want to subtract div height)
  s.left=Math.random()*window.innerHeight+'px'; // ... height ...
},2000)
div{position:fixed}
<div>div</div>

// with jQuery
setInterval(function () {
  $('#mydiv').css({
    top: Math.random() * ($(window).height() - $('#mydiv').height()) + 'px', // multiply random .width(0..1) value by window height minus div height
    left: Math.random() * ($(window).width() - $('#mydiv').width()) + 'px'
  })
}, 2000)
#mydiv{position:fixed}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">div</div>