Randomizing the position of an element after it's been clicked

Hi I’m trying to randomize the position of a circle after it’s been clicked to a new random position.

I thought this would work, but something still isn’t working right.

var circle = document.getElementById('circle');
var spaceWidth;
var spaceHeight;

function init() {
  spaceWidth = screen.height - circle.height;
  spaceHeight = screen.width - circle.width;

  circle.addEventListener('click', moveCircle)
}

function moveCircle(){
  circle.style.top = Math.round(Math.random() * spaceWidth) + 'px';

  circle.style.left = Math.round(Math.random * spaceHeight) + 'px';

}

As far as I can see, that init() doesn’t get called …

Hey michaelsndr thanks for responding. You’re right it hasn’t been called. I tried calling it in a few places, but couldn’t get it to work. I’m honestly not sure where I should be calling it.
( NOTE: I changed function name to initCircle.)

for example

  return {
    start(){
      initCircle();
      loseBanner.style.display = 'none';
      winBanner.style.display = 'none';
      currentGame = setInterval(game, 1000)
      increasing = true;
      count = 0;
      score = 0;
    },

and here

function gameClosure(){
  function game(){
    initCircle();
    loseBanner.style.display = 'none';
    winBanner.style.display = 'none';
    counter.style.display = 'block';
    increasing === true ? count++ : count = 0;
    counter.innerHTML = count;
    count === specifiedNumber ? increasing = false : increasing = true;
    if( count === specifiedNumber && score < 5) {
      losingBanner();
    } 
    if (count === specifiedNumber && score >= 5) {
      winningBanner();
    }
  }

The spaceWidth (and spaceHeight) here undefined:

image

Because there is no circle.height:

image

If your replace the .height with .offsetHeight, you get values:

image

image


Thank You michaelsndr, managed to figure it out.

1 Like