0
var element = document.getElementById('image1');

function leftArrowPressed () {
  element.style.left = parseInt(element.style.left) - 5 + 'px';
}

The code is for moving images with arrow keys. When element is a global variable it doesn't work but works when it's a local variable. Why?

Balthazar
  • 33,765
  • 10
  • 77
  • 104
Satvik A
  • 9
  • 5

1 Answers1

0

There aren't any problems with scope.

I don't see all code. I guess that a problem in this line because it's called when DOM element doesn't exist.

var element = document.getElementById("image1");

Try to use window.onload.

Stanislav Mayorov
  • 3,694
  • 4
  • 16
  • 42