Spot the bug - #175: Bouncing Saucer Sprite

Why is this bouncing saucer stuck in a frozen state?

const saucer = document.querySelector("#saucer");
const bounds = { min: 20, max: 420 };
let posX = 30;
let speed = 4;
let isDescending = false;

function updateSaucer() {
  posX += speed;

  if (posX >= bounds.max || posX <= bounds.min) {
    speed = -speed;
    isDescending = !isDescending;
  }

  const wobble = Math.sin(posX * 0.05) * 8;
  saucer.style.left = posX;
  saucer.style.top = `${80 + wobble}px`;
  saucer.style.transform = `rotate(${speed * 3}deg)`;

  requestAnimationFrame(updateSaucer);
}

requestAnimationFrame(updateSaucer);

Reply with what is broken and how you would fix it.

Spot the Bug answer: The ‘left’ CSS property is assigned a number without a unit.

The fix:
Change saucer.style.left = posX; to saucer.style.left = ${posX}px;.

Why:
When setting CSS properties like ‘left’ or ‘top’ directly via JavaScript’s style object, a unit (e.g., ‘px’, ‘em’, ‘%’) must be appended to numerical values. Without a unit, the browser interprets the assignment as invalid, and the style property is ignored, causing the saucer to remain at its initial ‘left’ position.

First-answer leaderboard

  1. @emmawalter5 - 12 (firsts) :trophy:
  2. @kirupa - 8 (firsts)
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)