I am new to javascript, please bear with me.
When the right arrow key is pressed I would like to change the div 100 pixels to the right. I use my own class to create a square and then try to change this instance position.
class Square {
constructor(length) {
this.width = length;
this.height = length;
this.div = document.createElement("div");
this.div.style.position = "absolute"; // to be able to move it
this.div.style.backgroundColor = "red";
this.div.style.width = length + "px";
this.div.style.height = length + "px";
document.body.appendChild(this.div);
this.xPos = 50;
this.div.style.left = this.xPos + "px";
}
}
var square2 = new Square(10);
window.addEventListener(
"keydown",
function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
switch (event.key) {
case "ArrowDown":
alert("ArrowDown");
// Do something for "down arrow" key press.
break;
case "ArrowUp":
// Do something for "up arrow" key press.
break;
case "ArrowLeft":
alert("ArrowLeft");
// Do something for "left arrow" key press.
break;
case "ArrowRight":
alert("ArrowRight");
square2.div.style.left += 100 + "px"; // this code does nothing?
break;
default:
return; // Quit when this doesn't handle the key event.
}
// Cancel the default action to avoid it being handled twice
event.preventDefault();
},
true
);
The code square2.div.style.left += 100 + "px";
does nothing.