Create divs in random places - javascript

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>

// 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>

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>

Related

Image is not stopping after reaching max width of the screen

My question is: how do I stop the image from moving to the left when it reaches the user's maximum screen width? I tried the below method by using JavaScript but it is not working. Also when the image reaches the user's maximum width, it should change the direction and return to where it was before.
<img src="plane.jpg" width="100px" height="100px" id="plane">
<script type="text/javascript">
var height = document.documentElement.clientHeight;
var width = document.documentElement.clientWidth;
var plane = document.getElementById("plane");
var leftpos = 0;
setInterval(function(){
if (leftpos != width) {
leftpos += 10;
plane.style.marginLeft = leftpos + 'px'
}else {
// change the direction
}
}, 50) // run code every 50 milliseconds
;
</script>
Appreciate your time and Take care.
You can check if the marginLeft and the width of the image plus 10 is less than window.innerWidth.
var height = document.documentElement.clientHeight;
var width = window.innerWidth;
var plane = document.getElementById("plane");
var leftpos = 0;
var right = true;
var id = setInterval(function() {
if (right && leftpos + plane.width + 10 <= width) {
leftpos += 10;
} else {
right = false;
leftpos -= 10;
if (leftpos <= 0) clearInterval(id);
}
plane.style.marginLeft = leftpos + 'px';
}, 50);
<img src="plane.jpg" width="100px" height="100px" id="plane">

Prevent Overlap in Dynamically Created Divs in JQuery

I am currently working on a webpage where an array of draggable images appear in random positions over time. I would like to prevent the newly created divs from overlapping as well as create a limit to how many new divs appear.
Below is the current code That I have;
var Images = ['https://material.io/icons/static/images/icons-180x180.png', 'https://iconscout.com/ms-icon-310x310.png', 'https://maxcdn.icons8.com/Share/icon/Food//cherry1600.png', 'https://lh3.googleusercontent.com/Ax2wQYxjDITuZEpc6K9EDYPG7C839tb4PApia4Tmf18u8XehB-twqhVgDVPgxxExkr4=w300',
'https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-256.png',
'http://files.softicons.com/download/game-icons/super-mario-icons-by-sandro-pereira/ico/Mushroom%20-%201UP.ico'],
screenWidth,
screenHeight;
$(document).ready(function() {
screenWidth = $(window).width();
screenHeight = $(window).height();
$(window).on('resize', function(){
screenWidth = $(window).width();
screenHeight = $(window).height();
})
setInterval(function () {
var x = Math.random() * screenWidth,
y = Math.random() * screenHeight;
addDiv(x, y);
}, 2000);
});
function addDiv(x,y) {
var randImageIndex = Math.floor( (Math.random() * (Images.length - 1) ) );
var Image = Images[randImageIndex];
var newDiv = $('<div class="object"><img src=' + Image + ' height="100" width="100"></div>').css({top:x,left:y});
$('body').append(newDiv);
newDiv.draggable();
newDiv.on('click', function() {
$(this).remove();
})
}
Any suggestions would be greatly appreciated!

How to use math.random() with for loop

I want to change the position of div with for loop ..
I made an animation .. When i click a div ( circle ) it moves to a position that is being determined with Math.random() ..
I dont want to click the div to move to another position .
I want to use for loop method and i want div to move another position in every 2 seconds or some seconds ..
Do you have any advise .. Thanks
Click to see how it is
$(document).ready(function () {
$("#circle").click(function () {
var width = Math.random();
var yeniwidth = width * 500;
margin = Math.round(yeniwidth);
$("#circle").css("margin-top", margin + "px");
var height = Math.random();
var yeniheight = height * 1000;
margin2 = Math.round(yeniheight);
$("#circle").css("margin-left", margin2 + "px");
});
});
Codepen
You don't really need a for-loop to do that. Instead of executing the code after clicking the div, you could just use the setInterval function instead:
$(document).ready(function () {
window.setInterval(function(){
var width = Math.random();
var yeniwidth = width * 500;
margin = Math.round(yeniwidth);
$("#circle").css("margin-top", margin + "px");
var height = Math.random();
var yeniheight = height * 1000;
margin2 = Math.round(yeniheight);
$("#circle").css("margin-left", margin2 + "px");
}, 5000);
});
Just change the number 5000 to adjust the time that should pass before the code is executed again (1000ms is 1 second).
On Codepen

Javascript - setInterval to change element's position

I'm trying to work out how to move an element across the screen. I don't want to use JQuery's animate() method because I need more precise control. Here is the basic idea:
http://jsfiddle.net/9RLkJ/
setInterval(function() {
var e = document.getElementById("aDiv");
// Increase the top position by 1 pixel
e.style.top = '+1px';
// If the top position is greater than 100px, set it to 100px
if (parseInt(e.style.top) > 100) { e.style.top = '100px'; }
}, 1000);
Thank you.
var e = document.getElementById("aDiv");
var s = 1;
setInterval(function(){
var eLeftPos = e.offsetLeft;
e.style.left = (eLeftPos + s) + 'px';
}, 1000);
The above code will move the box to right;
working demo move the box to bottom
var top= document.getElementById("aDiv").style.top;
setInterval(function() {
top += 1;
var e = document.getElementById("aDiv");
// Increase the top position by 1 pixel
e.style.top = top + 'px';
// If the top position is greater than 100px, set it to 100px
if (parseInt(e.style.top) > 100) { e.style.top = '100px'; }
}, 1000);

Adapt random image placement code for flexible layout

I'm looking for an effect very similar to this:
http://jsfiddle.net/G5Xrz/
function rnd(max) { return Math.floor(Math.random()*(max+1)) }
function showImage(container, maxwidth, maxheight, imgsrc, imgwidth, imgheight) {
var id = "newimage" + rnd(1000000);
$(container).append(
"<img id='" + id + "' src='" + imgsrc +
"' style='display:block; float:left; position:absolute;" +
"left:" + rnd(maxwidth - imgwidth) + "px;" +
"top:" + rnd(maxheight - imgheight) + "px'>");
$('#' + id).fadeIn();
return id;
}
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
But i'd prefer a flexible layout, ie images not bound by a div with predefined height and width, instead responding to the dimensions of the browser.
The following piece of code seems to have a more appropriate way of generating the random positions:
http://jsfiddle.net/Xw29r/15/
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
However I'm very much a beginner with javascript and I don't know how to combine the two.
Can anyone help?
Thanks
Take this part from the second code:
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
and use those variables h and w with the browser height and width (minus 50) as the appropriate parameters in this part of the first code:
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
Also, the first code has this HTML:
<div id="container" style="width:400px; height:600px; background: green; position:relative"></div>
That hard-codes the height and width at pixel values. You can use a CSS percentage value to make the width respond to the parent container's size. However, you will need JS to set the height properly; a percentage for the height does nothing
Putting that all together (and removing the "minus 50" part), you get this:
jsFiddle demo
<div id="container" style="width:100%; height:100px; background: green; position:relative"></div>
function adjustContainerHeight(height) {
$('#container').height(height);
}
adjustContainerHeight($(window).height());
setInterval(
function() {
var h = $(window).height();
var w = $(window).width();
adjustContainerHeight(h);
showImage("#container", w, h,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
This updates the height of the container when the page is first loaded, and once again whenever the random image is placed. More robust code would have a separate height-adjusting event handler that updates the height whenever the page size changes.

Categories