Question

so I have this code that is giving me a random number for both top and left attribute of some images.

    var random1 = Math.ceil(Math.random() * 500);
var random2 = Math.ceil(Math.random() * 500);

$(document).ready(function () {

    $('#randomp').css('top', random1);
    $('#randomp').css('left', random2);

});

The problem is that I would be prefer to randomize a number between 1 and 100%. Is that possible?

Was it helpful?

Solution

Math.floor(Math.random() * 100) + 1 + '%'

OTHER TIPS

Since Math.random returns number that is random, not less than 0 and less than 1, you have just to multiply result by 99 instead of 500 to get a number beetween 1 and 100%.

Finally, the code should be as follows:

var random1 = Math.round(Math.random() * 99) + 1;
var random2 = Math.round(Math.random() * 99) + 1;

This gives you a number between 0 and 100 (both included): Math.floor(Math.random() * 101);

  1. Math random will give you a number between 0 (included) and 1 (excluded)
  2. If you multiply that number with 101, it will give you a number between 0 (included) and 101 (excluded)
  3. Math.floor will return the the largest integer less than or equal to the above number.

Not sure if you want it rounded or not, so here's both:

console.log( rando(1, 100) + "%" );
console.log( rando(1, 100, "float") + "%" );
<script src="https://randojs.com/1.0.0.js"></script>

This uses randojs.com to make the randomness simple and readable. If you need to know more, check out the website.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top