jeudi 19 octobre 2017

generating a random position inside a div using javascript

Im looking for a way on generating a random position on my html div. I've created a javascript function which looks like this:

function randomInRange(min, max) {
    return(Math.floor((Math.random() * (max - min) + 1) + min));    
}  

I wanted to generate a random position in the div's css by changing (position:relative; left:0px; top:0px) the left and top attribute to the random generated number. I can't seem to find a max & min value for the function since the div uses percentages for the widths.

css of the div:

#stage {
    float: left;
    background-color: pink;
    width: 100%;
    height: 70%;
}

the function executes when i click a certain button

var button = document.getElementById("button");

button.onclick = function () {
    shape.style.left = randominrange(0, stage.style.width);
    shape.style.top = randominrange(0, stage.style.height);   
}
//the shape is a circle div that shows where the generated point is

i just started javascript a few days ago and cant seem to find a way to do it

Aucun commentaire:

Enregistrer un commentaire