user2900299
user2900299

Reputation: 57

I am having trouble placing a div in a random position

I am trying to randomly place a div, but I am getting a type error. It says the element is undefined, but I thought that I was defining it with the const line of line 1. In my CSS file, the position of the div is absolute and there's a background image set. I can tell in the console.log that I am getting the random numbers that I want. I am just having a little trouble attaching those coordinates to the div.

const animal = document.querySelectorAll('.animal');

function getRandomPos(animal) {
    var x = screen.width;
    var y = screen.height;
    var randomX = Math.floor(Math.random() * x);
    var randomY = Math.floor(Math.random() * y);
    console.log(randomX, randomY);

    let rect = animal.getBoundingClientRect();
    console.log(rect.top, rect.right, rect.bottom, rect.left);

    animal.style.left = randomX;
    animal.style.top = randomY;
}

Upvotes: 0

Views: 167

Answers (1)

Teddy Michels
Teddy Michels

Reputation: 116

One major issue was already addressed in the comments - querySelectorAll returns an HTMLCollection rather than a single element, so you'll need querySelector. Also, you'll need to add "px" units to the lines where you're setting the element's style (see below).

UPDATE

Questioner mentioned having multiple randomly moving elements, so I've added an example that includes how that might be done using IDs as an argument to the setRandomPos function.

function setRandomPos(target) {
  const element = document.getElementById(target);
  // var x = screen.width;
  var x = 400; // Just smaller numbers for the example
  // var y = screen.height;
  var y = 200;
  var randomX = Math.floor(Math.random() * x);
  var randomY = Math.floor(Math.random() * y);

  // Remember to add px for units
  element.style.left = randomX + 'px';
  element.style.top = randomY + 'px';
}
.randMove {
  position: fixed;
}

button {
  font-size: 20px;
  z-index: 1;
  position: relative;
}
<div id="animal" class="randMove">
  <img src="https://upload.wikimedia.org/wikipedia/en/thumb/e/e7/Animal_%28Muppet%29.jpg/220px-Animal_%28Muppet%29.jpg" alt="Animal">
</div>

<div id="grover" class="randMove">
  <img src="https://vignette.wikia.nocookie.net/muppet/images/f/f7/GroverFullFigure2.png/revision/latest?cb=20190222025220" alt="Grover">
</div>

<button onClick="setRandomPos('animal')">Move Animal</button>
<button onClick="setRandomPos('grover')">Move Grover</button>

Upvotes: 1

Related Questions