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?

Preview
  • 34,540
  • 10
  • 86
  • 108
Satvik A
  • 19
  • 7

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,961
  • 5
  • 20
  • 42