Grecdev
Grecdev

Reputation: 959

It doesn't increment the position

I have the following code, i want to move a box my pressing arrow(left arrow in this case) but is adding only once to left property. If i press multiple times on the left arrow it remains on the same spot. Can't figure why..

const box = document.querySelector('div');
const body = document.querySelector('body');

body.addEventListener('keydown', move);

function move(event) {
    let ddd = event.which || event.keyCode;
    let left = 0;
    box.style.position = 'absolute';
    if(ddd === 37) {
        left += 5;
        box.style.left = left + 'px';
    }
}

Upvotes: 0

Views: 45

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

That's because you're resetting the value of left every time. Store left outside of move to prevent resetting it.

const box = document.querySelector('div');
const body = document.querySelector('body');
let left = 0;

body.addEventListener('keydown', move);

function move(event) {
    let ddd = event.which || event.keyCode;
    box.style.position = 'absolute';
    if(ddd === 37) {
        left += 5;
        box.style.left = left + 'px';
    }
}

Upvotes: 2

Related Questions