The code doesn't work why?

The code you posted contains a few errors, whether those are in the book or you make a mistake copying it I don’t know.

  1. As pointed out, you cannot have multiple elements with the same ID
  2. You have a brace that is misplaced, causing your if statements to be incorrectly nested.

I created a fiddle with the corrected code, and used verbose variable names so perhaps you can read it and understand what it does.

document.getElementById("car").addEventListener("mousemove", opa)
let lastHorizontalPosition = 0
let currentOpacity = 0

function opa() {
  let currentHorizontalPosition = event.pageX
  if (currentHorizontalPosition - lastHorizontalPosition > 3) {
    if (currentOpacity <= 1) {
      currentOpacity += 0.01
      document.getElementById("car").style.opacity = currentOpacity
      lastHorizontalPosition = currentHorizontalPosition
    } else {
      currentOpacity = 1
    }
  }
  if (lastHorizontalPosition - currentHorizontalPosition > 3) {
    if (currentOpacity > 0) {
      currentOpacity -= 0.01
      document.getElementById("car").style.opacity = currentOpacity
      lastHorizontalPosition = currentHorizontalPosition
    } else {
      currentOpacity = 0
      lastHorizontalPosition = 0
    }
  }
}

Basically, as you move the mouse across the page to the right, the opacity of the image increases. As you move the mouse back to the left, it decreases. The comparison to > 3 or < 3 is so that tiny mouse movements don’t cause a change. The mouse must move at least 3 pixels to make a change.

4 Likes