Home » Javascript » Random position of elements within a defined range

Random position of elements within a defined range

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have three elements (div) within the body.

Each of them should have a randomly generated distance to the left edge of the viewport. In addition, each element should maintain a minimum distance of 20 pixels to the left and 20 pixels to right edge of the viewport – in other words – they should use a specific range of ​​the viewport.

Preparation:

  1. Get elements by their tagname:

layer = document.getElementsByTagName(‘div’);

  1. Determine the area where the layers should be placed:

var min = 20;

var max = window.innerWidth – layer [0] .getBoundingClientRect(). width – 20;

  1. Convert collection to a “real” array:

layer = Array.prototype.slice.call (layer,0);

  1. Execute function “test” once for each element:

layer.forEach (test);

My function:

function test(el)
{

distance = Math.floor(Math.random() * (max – min + 1)) + min;

if (distance >= min && distance <= max)
{

el.style.left = distance + “px”;

}

}

My problem / my question:

My function “test” causes the random value stored in “distance” not to be transmitted in any case, namely whenever the random value can not satisfy the condition. The following should be the solution – I thought …

do
{

distance = Math.floor(Math.random() * (max – min + 1)) + min;

}

while (distance >= min && distance <= max)
{

el.style.left = distance + “px”;

}

Unfortunately, my experiments are not successful. How can I solve the problem ?

Answers: