I want to make a div that is full width on the page. It's a container. Then I want to fill it in with divs, and width of each div is 50*n, where n is a randomly generated number. Assume I have a container div with width of 1240px. Now I run a JS function that fills it with e.g. 10 divs with different widths. Now if I sum up all inner divs widths, I get 1240px.
This way I always know that when I run filling function, I get a collection of divs that altogether always are 1240px. Number of divs shouldn't be a fixed number, so there can be 4 or 7 divs. The number of divs amount is generated randomly. Then, if there is some space left, for 1240 px this number is 40px I suppose, it is filled with some dummy div that doesn't have to be of 50*n width.
I have created a function but it doesn't always work as supposed to.
function generateItems() {
originalwidth = $(document).width() - 40;
var fullwidth = 0;
var counter = 0;
do{
var randomnumber = 1 + Math.floor(Math.random() * 4);
tempwidth = 50 * randomnumber;
fullwidth += tempwidth;
if (fullwidth > originalwidth) {
$('#questions').append('<div class="question-area" style="width:' + (originalwidth - fullwidth) + 'px;"><strong>' + (originalwidth - fullwidth) + '</strong></div>');
break;
}
width_padding = tempwidth;
$('#questions').append('<div class="question-area" style="width:' + width_padding + 'px;">' + width_padding + '</div>');
counter++;
}
while (true);
}
I am not even sure it's a good way I have chosen to solve such a task. Please share your thoughts on how to better do this.
I've refactored the code from your answer a bit.
See: http://jsfiddle.net/thirtydot/Bk2yw/
function generateItems() {
var slotWidth = 50,
maxSlots = 3,
thisSlotNum, thisWidth;
var remainingSlots = Math.floor($('#questions').width() / slotWidth),
remainingWidth = $('#questions').width() % slotWidth;
while (remainingSlots > 0) {
thisSlotNum = Math.min(remainingSlots, 1 + Math.floor(Math.random() * maxSlots));
remainingSlots -= thisSlotNum;
thisWidth = thisSlotNum * slotWidth;
$('#questions').append('<div class="question-area" style="width:' + thisWidth + 'px;"><strong>' + thisWidth + '</strong></div>');
}
if (remainingWidth) {
$('#questions').append('<div class="question-area" style="width:' + remainingWidth + 'px;"><strong>' + remainingWidth + '</strong></div>');
}
}
I played a little more with the code and it seems I made it work properly, though I am sure there is something to improve.
Here is the code:
function generateItems() {
originalwidth = $(document).width() - 40;
$('#questions').css('width', originalwidth);
var fullwidth = 0;
var counter = 0;
do{
var randomnumber = 1 + Math.floor(Math.random() * 4);
tempwidth = 50 * randomnumber;
fullwidth += tempwidth;
if (fullwidth > originalwidth) {
$('#questions').append('<div class="question-area" style="width:' + (originalwidth + tempwidth - fullwidth) + 'px;"><strong>' + (originalwidth + tempwidth - fullwidth) + '</strong></div>');
break;
}
width_padding = tempwidth;
$('#questions').append('<div class="question-area" style="width:' + width_padding + 'px;">' + width_padding + '</div>');
counter++;
}
while (true);
}
Here is an screenshot of how it works. The bottom row is the result for another width of the page.
A couple of problems:
fullwidth += tempwidth;
if (fullwidth > originalwidth) {
$('#questions').append('<div class="question-area" style="width:' + (originalwidth - fullwidth) + 'px;"><strong>' + (originalwidth - fullwidth) + '</strong></div>');
break;
}
Here you have already "gone over" the original width with the fullwidth variable, so when you do originalwidth - fullwidth it's always negative (by definition because fullwidth > originalwidth).
Another problem is that if the random width is for example 150 pixels and you have 140 pixels of space left, your code considers that as space running out and puts in the dummy div of 140 px. It's not clear from your question but you probably want a 100 px block and the rest filled with a 40 px block.
Here's a working version:
function generateItems() {
var originalwidth = $(document).width() - 40;
var fullwidth = 0;
var counter = 0;
do{
var randomnumber = 1 + Math.floor(Math.random() * 3);
var tempwidth = 50 * randomnumber;
if (fullwidth + tempwidth > originalwidth) {
var diff = originalwidth - fullwidth;
if( originalwidth - fullwidth > 50 ) {
tempwidth = diff - ( diff % 50 );
}
else {
$('#questions').append('<div class="question-area" style="width:' + diff + 'px;"><strong>' + diff + '</strong></div>');
break;
}
}
fullwidth += tempwidth;
$('#questions').append('<div class="question-area" style="width:' + tempwidth + 'px;">' + tempwidth + '</div>');
counter++;
}
while (true);
}
Related
I have some JavaScript code and it's working (kind of). I'd like to condense it somehow, maybe grab both the CSS selectors at once and iterate through them with a forEach() loop of some kind.
Right now, the top value for both stars gets the same value, eg style="top: 60%". I'd like to have them get different random values for the top, left, right and transform.
I realize the querySelectorAll will return a NodeList, and can be converted to an array, but I cannot figure out how to do this and have it so the .shooting-star-right gets different values using the Math.random section.
I've tried this:
var stars = document.querySelectorAll('.shooting-star, .shooting-star-right');
for (let el of stars) {
shootingStar();
}
I've also tried this:
var stars = document.querySelectorAll('.shooting-star, .shooting-star-right');
stars.forEach(function() {
shootingStar();
});
Here is my working (although quite messy) code => any help is much appreciated :)
init: () => {
let star = document.querySelector('.shooting-star');
let starRight = document.querySelector('.shooting-star-right');
const shootingStar = () => {
setInterval(() => {
let topPos = Math.floor(Math.random() * 80) + 1,
topPosRight = Math.floor(Math.random() * 80) + 1,
leftPos = Math.floor(Math.random() * 20) + 1,
rightPos = Math.floor(Math.random() * 20 + 1),
trans = Math.floor(Math.random() * 180) + 1,
transRight = Math.floor(Math.random() * 220) + 1;
topPos = topPos + '%',
topPosRight = topPosRight + '%',
leftPos = leftPos + '%',
rightPos = rightPos + '%',
trans = trans + 'deg',
transRight = transRight + 'deg';
star.style.top = topPos,
star.style.left = leftPos,
star.style.transform = 'rotate(' + '-' + trans + ')';
starRight.style.top = topPosRight,
starRight.style.right = rightPos,
starRight.style.transform = 'rotate(' + transRight + ')';
}, 9000);
};
shootingStar();
}
The element el has to be used in the forEach or for of loop. For example (not tested):
function setStyles(name, style) {
for (let el of document.getElementsByClassName(name)) el.style = style;
// or document.getElementsByClassName(name).forEach(el => el.style = style);
}
const r = n => Math.random() * n | 0 + 1;
setStyles('shooting-star', `top:${r(80)}%,left:${r(20)}%,transform:rotate(-${r(180)}deg)`);
setStyles('shooting-star-right', `top:${r(80)}%,right:${r(20)},transform:rotate(${r(220)}deg)`);
Well, this is lesser code:
star.style.top = (Math.floor(Math.random() * 80) + 1) +"%";
star.style.left = (Math.floor(Math.random() * 20) + 1) +"%;
etc.
Also, since you already use transform, you might as well use it for positioning. It works much better than setting left and top when used for animation.
let leftPos = Math.floor(Math.random() * 80) + 1
let topPos = Math.floor(Math.random() * 20) + 1
star.style.transform = 'translate('+ leftPos +'px, '+topPos +'px) rotate(' + '-' + trans + ')';
If you guys are interested, I ended up taking both your comments and finding a solution. I think this looks pretty good.
I really appreciate the assistance
const randomNum = (low, high) => {
let r = Math.floor(Math.random() * (high - low + 1)) + low;
return r;
};
const shootingStars = (name) => {
const stars = document.querySelectorAll(name);
const starsArray = [...stars];
setInterval(() => {
starsArray.forEach(el => {
el.style.cssText = 'transform: rotate(' + randomNum(0, 180) + 'deg' + ') translateY(' + randomNum(0, 200) + 'px' + ')';
});
}, 9000);
};
shootingStars('.shooting-star');
shootingStars('.shooting-star-right');
I have the following JavaScript code to update tiles on a page:
var delayMinimum = 1000;
var delayMaximum = 5000;
function UpdateTiles()
{
var width = 0;
var delay = 0;
var percent = 0;
var divNameLabel = "";
var divNameValue = "";
var divNameProgress = "";
if (Math.floor((Math.random() * 100) + 1) > 30)
{
percent = Math.floor((Math.random() * 100) + 1);
width = Math.floor(80 * percent / 100);
divNameLabel = "DivDashboardTileTemplatesLabel";
divNameValue = "DivDashboardTileTemplatesValue";
divNameProgress = "DivDashboardTileTemplatesProgress";
document.getElementById(divNameValue).innerText = percent.toString() + "%";
$("div#" + divNameProgress).animate({ width: (width.toString() + "px"), }, delayMinimum);
}
if (Math.floor((Math.random() * 100) + 1) > 30)
{
percent = Math.floor((Math.random() * 100) + 1);
width = Math.floor(80 * percent / 100);
divNameLabel = "DivDashboardTileDocumentsLabel";
divNameValue = "DivDashboardTileDocumentsValue";
divNameProgress = "DivDashboardTileDocumentsProgress";
document.getElementById(divNameValue).innerText = percent.toString() + "%";
$("div#" + divNameProgress).animate({ width: (width.toString() + "px"), }, delayMinimum);
}
if (Math.floor((Math.random() * 100) + 1) > 30)
{
percent = Math.floor((Math.random() * 100) + 1);
width = Math.floor(80 * percent / 100);
divNameLabel = "DivDashboardTileFormsLabel";
divNameValue = "DivDashboardTileFormsValue";
divNameProgress = "DivDashboardTileFormsProgress";
document.getElementById(divNameValue).innerText = percent.toString() + "%";
$("div#" + divNameProgress).animate({ width: (width.toString() + "px"), }, delayMinimum);
}
delay = Math.floor((Math.random() * (delayMaximum - delayMinimum)) + delayMinimum);
window.setTimeout(UpdateTiles, delay);
}
$(document).ready(UpdateTiles);
This works but any tiles updated in every iteration are updated all at once. How could I have independent timers with different intervals for each update?
Consider the following JSFiddle as a solution.
I have simplified it by using 1 function for all 3 calls and they now update at different (random) times. The key to recalling the update is the following line.
setTimeout(function () {updateTileSet(label,value,progress)}, delay);
You only have one timer: window.setTimeout(UpdateTiles, delay), add more timers as you need i order to have multiple timers.
Why did you duplicate the code 3 times?
Use functions instead and set the timeout in each one of them.
How can i create something like this in HTML using javascript?
Actually I know how to create rectangles in HTML but want to do something like this. HTML canvas can be of any size but whenever page is loaded multiple squares are generated with random sizes and colors without overlapping. When I'm trying to do this rectangles are generated in a list form. I'm a web developer(ruby on rails oriented) but new to such javascript stuff. Any help will be appreciated.
html:
<body>
<div id="randBlock" >
</div>
</body>
javascript:
(function makeDiv(){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('#randBlock').css({
'width':divsize+'px',
'height':divsize+'px',
'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'
}).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
$(this).remove();
makeDiv();
});
})();
A solution with canvas (so I understand the question).
With built-in collision detecting isInside().
Edit: Better random support, does not run forever, a hint from Drawing a 1px thick line in canvas creates a 2px thick line and a little bit from this answer Random Color generator in Javascript
function getRandomColor() {
var color = '#';
for (var i = 0; i < 6; i++) {
color += (Math.random() * 16 | 0).toString(16);
}
return color;
}
function Point(x, y) {
this.x = x;
this.y = y;
}
function Rectangle(p1, p2) {
this.p1 = p1;
this.p2 = p2;
}
Rectangle.prototype.isInside = function (r) {
function check(a, b) {
return (
a.p1.x <= b.p1.x && b.p1.x <= a.p2.x && a.p1.y <= b.p1.y && b.p1.y <= a.p2.y ||
a.p1.x <= b.p2.x && b.p2.x <= a.p2.x && a.p1.y <= b.p2.y && b.p2.y <= a.p2.y ||
a.p1.x <= b.p2.x && b.p2.x <= a.p2.x && a.p1.y <= b.p1.y && b.p1.y <= a.p2.y ||
a.p1.x <= b.p1.x && b.p1.x <= a.p2.x && a.p1.y <= b.p2.y && b.p2.y <= a.p2.y
);
}
return check(this, r) || check(r, this);
}
function generateRectangles() {
function p() { return Math.random() * 300 | 0; }
function s() { return 50 + Math.random() * 150 | 0; }
var rectangles = [],
r, size, x, y, isInside, i, counter = 0;
for (i = 0; i < 20; i++) {
counter = 0;
do {
counter++;
x = p();
y = p();
size = s();
r = new Rectangle(new Point(x, y), new Point(x + size, y + size));
isInside = rectangles.some(function (a) {
return a.isInside(r);
});
} while (isInside && counter < 1000);
counter < 1000 && rectangles.push(r);
}
return rectangles;
}
function drawRectangles(rectangles) {
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
rectangles.forEach(function (a) {
ctx.lineWidth = 1;
ctx.strokeRect(a.p1.x + 0.5, a.p1.y + 0.5, a.p2.x - a.p1.x - 1, a.p2.y - a.p1.y - 1);
ctx.fillStyle = getRandomColor();
ctx.fillRect(a.p1.x + 0.5, a.p1.y + 0.5, a.p2.x - a.p1.x - 1, a.p2.y - a.p1.y - 1);
});
}
var rectangles = generateRectangles();
drawRectangles(rectangles);
<canvas id="canvas" width="500" height="500"></canvas>
You already have it drawing one random square with random position. It's easy to go from there to drawing many - simply have a loop for adding more than one div. Of course, then you need to give each one a random id, but that's easy enough. The problem is that this will allow overlapping.
Simplest case: allowing overlap
function makeDiv(i) {
var divsize = ((Math.random() * 100) + 50).toFixed();
var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
var divid = 'randBlock' + i;
$('#randBlock').append("<div id='" + divid + "'>");
$('#' + divid).css({
'width': divsize + 'px',
'height': divsize + 'px',
'background-color': color,
'position': 'absolute',
'left': posx + 'px',
'top': posy + 'px'
});
}
for (var i = 0; i < 10; ++i) {
makeDiv(i);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="randBlock">
</div>
</body>
If you want to guarantee it doesn't overlap, you have a lot more work to do, unless there's some CSS magic you can do, which is very possible, but I'm not aware of it. You would have to track the position and size of each square, and only fit the results into areas that are clear.
Depending on your exact requirements, your algorithm will be different. You're going to have to have some constraint - either in the maximum size of the squares, the requirement on overlapping, a maximum number of squares that you want to fit, or allow the squares to become increasingly small. I'll give you a verbal walkthrough for two of these. There's a working snippet for the grid idea. From what you added in the comments, that may be sufficient.
You've already built in a fixed size, so maybe the best idea is to use that size as a basis, and create a grid. In that case, you'll know you can have one square in each gridsquare. Have an array that stores each gridsquare position, and randomly choose from (1 to the length of that array) - 1. In that gridsquare, fit a square, very similarly to the function you currently have. Its size is the max you already have set, and its position within that box can be random based on the size.
Gridded case
var fixedScale = 100;
var fixedConstant = 50;
var fixedMax = fixedScale + fixedConstant;
var gridCols = (($(document).width() / fixedMax) + 1).toFixed();
var gridRows = (($(document).height() / fixedMax) + 1).toFixed();
var grid = [];
for (var row = 0; row < gridRows; ++row) {
for (var col = 0; col < gridCols; ++col) {
var index = row * gridCols + col;
grid[index] = {row: row, col: col};
}
}
function makeDiv(i) {
var gridId = Math.floor(Math.random() * grid.length);
var divsize = ((Math.random() * fixedScale) + fixedConstant).toFixed();
console.log(gridId + ", grid.length = " + grid.length);
var color = '#' + Math.round(0xffffff * Math.random()).toString(16);
var posx = grid[gridId].col * fixedMax;
var posy = grid[gridId].row * fixedMax;
var offsetx = (Math.random() * (fixedMax - divsize)).toFixed();
var offsety = (Math.random() * (fixedMax - divsize)).toFixed();
posx = +posx + +offsetx;
posy = +posy + +offsety;
var divid = 'randBlock' + i;
grid.splice(gridId, 1);
$('#randBlock').append("<div id='" + divid + "'>");
$('#' + divid).css({
'width': divsize + 'px',
'height': divsize + 'px',
'background-color': color,
'position': 'absolute',
'left': posx + 'px',
'top': posy + 'px'
});
}
for (var i = 0; i < 10; ++i) {
makeDiv(i);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="randBlock">
</div>
</body>
You can have infinite (but diminishing squares) using the following fact: any time you add a square into an empty area, it will leave four rectangles of remaining space in that area. Any time you make a colored square, you could actually make 5 divs: the colored square, the empty area on its top, its right, its bottom and its left. Attribute the empty ones with a specific class. Then, look through all divs that have that "empty" class, and set your max size to the max of the empty divs. When you create your next colored square, pick a random div that is at least as big as the square.
Obviously, the code for these is not entirely trivial. The choice you make in your requirements and constraints will have a huge impact on your coding effort.
Hi i want to calculate the position of the Div. Pardon me if i am not able to explain it properly but i will try to explain everything in the simplest way. I am creating sidepanel ad and to place the panels i want the position of the width. When i upload the script on my server then i get a small script which we place on the publisher website and where our script runs inside the iframe. I want to get the position of the div which has a class 'content'. Here is the screen shot.
in the above screenshot the yellow highlighted script is calculating the position of the div class="content" which is in red box. My code was working fine but on the publisher site it was not working fine and i was only able to get only two Divs whose id is like ebDiv..... (these divs are above the yellow highlighted js).
Then i found out to read the parentDiv in order to get the content positions.
i wrote this code.
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
alert(parentDiv[i].offsetWidth);
alert(parentDiv[i].offsetLeft);
}
The width is calcuated as 1010 which is fine but i am just missing left positioning which i am getting using parentDiv[i].offsetLeft is 2.
Above the screenshot has width 1010 which is fine but left positioning is not correct.
i had this code to calculate the width.
function ReadDivPos(selector) {
var _divPos = "";
$(selector).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
});
return _divPos;
}
console.log(ReadDivPos(".content"));
when i am using the same code to calculate the positioning then it is not working .
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
$(parentDiv[i]).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
}
}
Can someone me explain me how to fix this. Jquery/Javascript anythingwould be fine. I am not good in the frontend things so i am sorry if i could not explain it better. Thanks in advance
Here is a function used to get the position on the page of an element:
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
Used like this:
var pos = getPosition(element);
var x = pos["x"];
var y = pos["y"];
I'm not sure if this is exactly what you need, but if not maybe you can tweak it to fit your situation
I have the following JavaScript; the intent is that circles will bounce on the screen, off all edges.
I went to a variable storing the window's height and width, because I thought failure to bounce off the bottom of the screen might because the node was progressively expanding, so my original check against jQuery(window).height() was pointless.
However, after having addressed this way of making a window bouncy on the edges, or tried to (it's at http://cats.stornge.com), I have not seen a ball bounce off one edge of the window, and if you watch your scrollbar, you can see that they are going well beyond the original bottom of the window as they fall.
var viewport_height = jQuery(window).height()
var viewport_width = jQuery(window).width();
var available_images = ['red.png', 'orange.png', 'yellow.png',
'green.png', 'blue.png', 'purple.png', 'brown.png', 'black.png',
'grey.png']; //, 'white.png'];
var bodies = [];
for(var i = 0; i < 3; ++i)
{
body = {id: i, velocity_y : Math.random(),
velocity_x: Math.random() * 10 - 5,
position_x: Math.random() * viewport_width - 100,
position_y: Math.random() * viewport_height - 100};
document.write('<img id="' + i + '" src="' + available_images[Math.floor(Math.random() * available_images.length)] + '" style="z-index: ' + i + '" />');
bodies[bodies.length] = body;
}
function iterate()
{
for(var index = 0; index < bodies.length; ++index)
{
bodies[index].velocity_y += .1;
bodies[index].position_x += bodies[index].velocity_x;
bodies[index].position_y += bodies[index].velocity_y;
var position = jQuery('#' + index).position();
if (position.top + 100 > viewport_height)
{
bodies[index].velocity_y = - bodies[index].velocity_y;
bodies[index].position_y = viewport_height - 100;
}
if (position.top < 0)
{
bodies[index].velocity_y = - bodies[index].velocity_y;
bodies[index].position_y = 0;
}
if (position.left > viewport_width - 100)
{
bodies[index].velocity_x = -bodies[index].velocity_x;
bodies[index].position_x = viewport_width - 100;
}
jQuery('#' + index).css('margin-top',
bodies[index].position_y + 'px');
jQuery('#' + index).css('margin-left',
bodies[index].position_x + 'px');
}
}
setInterval(iterate, 30);
I'd love to see how to make this code set bouncy walls at the boundaries of the original viewport.
When changing the margin-top and margin-left, the width and height of the window started to change as well.
I got this to work by changing the css() calls setting margin-top and margin-left to offset(). I also added another if statement to make sure the balls bounced off the left-hand side as well:
var viewport_height = jQuery(window).height()
var viewport_width = jQuery(window).width();
var available_images = ['red.png', 'orange.png', 'yellow.png',
'green.png', 'blue.png', 'purple.png', 'brown.png', 'black.png',
'grey.png']; //, 'white.png'];
var bodies = [];
for(var i = 0; i < 3; ++i)
{
body = {id: i, velocity_y : Math.random(),
velocity_x: Math.random() * 10 - 5,
position_x: Math.random() * viewport_width - 100,
position_y: Math.random() * viewport_height - 100};
document.write('<img id="' + i + '" src="http://cats.stornge.com/' + available_images[Math.floor(Math.random() * available_images.length)] + '" style="z-index: ' + i + '" />');
bodies[bodies.length] = body;
}
function iterate()
{
for(var index = 0; index < bodies.length; ++index)
{
bodies[index].velocity_y += .1;
bodies[index].position_x += bodies[index].velocity_x;
bodies[index].position_y += bodies[index].velocity_y;
var position = jQuery('#' + index).position();
if (position.top + 100 > viewport_height)
{
bodies[index].velocity_y = - bodies[index].velocity_y;
bodies[index].position_y = viewport_height - 100;
}
if (position.top < 0)
{
bodies[index].velocity_y = - bodies[index].velocity_y;
bodies[index].position_y = 0;
}
if (position.left > viewport_width - 100)
{
bodies[index].velocity_x = -bodies[index].velocity_x;
bodies[index].position_x = viewport_width - 100;
}
if (position.left < 0)
{
bodies[index].velocity_x = -bodies[index].velocity_x;
bodies[index].position_x = 0;
}
jQuery('#' + index).offset({top: bodies[index].position_y, left: bodies[index].position_x });
}
}
setInterval(iterate, 30);