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
  • 35,317
  • 10
  • 92
  • 112
Satvik A
  • 21
  • 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
  • 4,298
  • 5
  • 21
  • 44