0

need to move div, inside of another div. Left and right direction is working, but up and down isn't working. What I do wrong?
Here is my code:

var mover = document.getElementById('mover');
var wrapper = document.getElementById('wrapper');
var left = 0;
var top = 0;

function move(e) {
if (e.keyCode == 39){
    left +=20;
    mover.style.left = left + 'px';
}

if (e.keyCode == 37){
    left -=20;
    mover.style.left = left + 'px';
}

if (e.keyCode == 40){
    top +=20;
    mover.style.top = top + 'px';
}

if (e.keyCode == 38){
    top -=20;
    mover.style.top = top + 'px';
}

}

document.onkeydown = move;



// 37left 38up 39right 40down
Taras Furman
  • 45
  • 1
  • 6
  • 2
    It’s because you use the variable name `top` globally. At this level it refers to `window.top` which cannot be a number and possibly cannot be changed due to security reasons. Either rename it, or wrap everything in a function to make it local, or use `const` or `let` instead of `var`. – Sebastian Simon Jul 08 '18 at 21:07
  • 1
    I'd suggest that you never use global variables like that, simply specifying `var x = ...` in the global scope. Rather, make, for example, an object called "globals" (`let window.globals = {}`) and then put your global variables inside it (e.g.: `globals.top = '30px';`). This way you'll avoid conflicts and other problems (like redeclaring later on `var x = ...`) – flen Jul 08 '18 at 21:12
  • 2
    @flen But then, what if a built-in global `globals` is introduced that your `window.globals` will clash with? This would pollute the global namespace which is equally bad. `let window.globals` is invalid, btw. – Sebastian Simon Jul 08 '18 at 21:15
  • @Xufox true, but what would you suggest in turn? I think it's better to have only one global object than having multiple global objects. One can use a very strange name, like `myGlobal4x9Y` to make sure there won't be conflicts. Oh, and you are spot on: `let window.globals` is of course invalid, I meant `window.globals = {}` or `let globals = {}` but I wrote it incorrectly – flen Jul 08 '18 at 21:18
  • 1
    @flen There are two alternatives I’ve described in my first comment and in the linked post: use `const` or `let` or wrap everything in a function, like I’ve done in the linked post. – Sebastian Simon Jul 08 '18 at 21:19

0 Answers0