Reputation: 17
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>
Upvotes: 0
Views: 2581
Reputation: 10879
// 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>
Upvotes: 2
Reputation: 1237
Just get width and height of document and use that to generate random number. You already have created the element in html, so no need to redo all that in JS.
In your specs you wanted every 2 seconds, so that would be 2000 ms in your timer.
In your timer function you would simply add the left and top of element with the new random numbers.
var blueMassElement = document.getElementById('bluemass');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
window.setInterval(function() {
// Create the divs in here
currentTop = Math.floor(Math.random() * documentHeight) + 1;
currentLeft = Math.floor(Math.random() * documentWidth) + 1;
blueMassElement.style.top = currentTop + "px";
blueMassElement.style.left = currentLeft + "px";
}, 2000);
#bluemass {
position:absolute;
}
<div id="bluemass" class="bluemass">
<img height="35" width="35" src='http://vignette4.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437' />
</div>
Upvotes: 0