mardi 22 mars 2022

Random position on X Axies

I'm trying to randomize position my div on the x axies. As default my div value is 5em (console.log(balloon.offsetWidth) => 80 in px)

get random number between 2 numbers:

function getRandomNumber(min:number, max:number){
    return Math.floor(Math.random() * (max - min) + min);
}

setting random position among the body width - the width of the div to prevent overflow

function setBalloonRandomXAxies(balloon:HTMLDivElement){
    balloon.style.left = `${getRandomNumber(0, (body.offsetWidth - balloon.offsetWidth))}px`
}

I'm still getting results bigger than: (body width - balloon width).

this works but, not dynamic maybe my div will change sizes sometimes

balloon.style.left = `${getRandomNumber(0, (body.offsetWidth - 80))}px`

Any helpers out there ?




Aucun commentaire:

Enregistrer un commentaire