louiecodes
louiecodes

Reputation: 23

Math.random() generating a single random number

I am creating a keyboard that creates divs upon key presses. (I already have the keyboard part figured out) I want each div to be placed randomly while still clustering by letter. I'm attempting to do this by adding a random integer between 1 and 20 to the existing ".aclass" top and left styling.

var min=1; 
var max=20;  
var random = Math.floor(Math.random() * (+max - +min) + +min);
var newtopa= $('.a').position().top + random;
var newlefta = $('.a').position().left + random;

function createElement(k) {  
  if (k == "a" || k == "A") { 
    $(".aclass").append('<div class="a" style="top:'+newtopa+'px;left:'+newlefta+'px;"></div>');
  }

However, my Math.random line is only returning a single random number. Everytime I press 'a' and create a div, it gets placed in the same place rather than randomly.

Upvotes: 1

Views: 62

Answers (2)

Isabella
Isabella

Reputation: 404

It's because by doing that you're only calling the Math.random() function once, whereas you'd need to generate a random number every time you press the key.

You could try doing that by making sure Math.random() is executed every time you run createElement().

Upvotes: 2

nathan.medz
nathan.medz

Reputation: 1603

You're declaring your random number outside of your createElement function, so you only create one, then use it each time you call createElement.

var min=1; 
var max=20; 

function createElement(k) {  

    var random = Math.floor(Math.random() * (+max - +min) + +min);
    var newtopa= $('.a').position().top + random;
    var newlefta = $('.a').position().left + random;
    if (k == "a" || k == "A") { 
        $(".aclass").append('<div class="a" style="top:'+newtopa+'px;left:'+newlefta+'px;"></div>');
    }

Also, you didn't specify what your newtopa and newlefta are supposed to give, but currently you'll just get the position of the first element with that class which seems unlikely to be what you want.

Upvotes: 2

Related Questions