How to change the location of an element after clicking on it on JS

Issue

I made a circle that moves to a random point on the screen after a page refresh. But the problem is that I need it to work without refreshing the page and only after clicking on the circle. There was also a problem with the circle going off the screen. That is, the circle sometimes appears outside the screen

I wrote the following code:

let elem = document.querySelector('button');
let randX = Math.random();
let randY = Math.random();
let randXMult = randX * 100;
let randXP = randXMult + "%";
let randYMult = randY * 100;
let randYP = randYMult + "%";

elem.style.left = randYP;
elem.style.top = randXP;
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  border: none;
  box-sizing: border-box;
}

body main html {
  width: 100%;
  height: 100%;
  position: relative;
}

button {
  width: 200px;
  height: 200px;
  border-radius: 100%;
  background: rgb(167, 163, 163);
  position: absolute;
}
<main>
  <button></button>
</main>

Solution

You can use a function to do that

I test this code and click it over 100 times

let elem = document.querySelector('button');

const changePosition = () => {
  let randX = Math.random();
  let randY = Math.random();
  const circleSize = {
    width: elem.clientWidth,
    heigth: elem.clientHeight
  };

  const windowWidth = window.innerWidth - circleSize.width;
  const windowheigth = window.innerHeight - circleSize.heigth;

  let randXMult = windowheigth * randX;
  let randXP = randXMult + 'px';
  let randYMult = windowWidth * randY;
  let randYP = randYMult + 'px';


  elem.style.left = randYP;
  elem.style.top = randXP;
};

elem.addEventListener('click', changePosition);
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  border: none;
  box-sizing: border-box;
}

body main html {
  width: 100%;
  height: 100%;
  position: relative;
}

button {
  width: 200px;
  height: 200px;
  border-radius: 100%;
  background: rgb(167, 163, 163);
  position: absolute;
}
<main>
  <button></button>
</main>

Answered By – Sobhan Esfandiary

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published