How to call a function when the function requires to move a div box when the left key is clicked?

43 Views Asked by At

# After writing the function I am stuck on how to call the function.

> window.addEventListener("keydown",function(e){
  if ((e.keycode==37)||(e.keycode==39)){
    myFunction(e.key);
> function myFunction(s){
  if (s =="ArrowLeft"){
    let objectLR = object.style.left;
    let objectPx = objectLR.slice(-2);
    objectLR = objectLR.Replace(objectPx, " ");
    objectLR = parseFloat(objectLR)- 10;
    objectLR+= "px";
    object.style.left = objectLR;
  }
}

Now I dont how to call the function.

1

There are 1 best solutions below

0
SaiMyo Myat On

I'm not sure what you really want to do. Anyway, if you add an event listener to window, the event will trigger every time your event happens on your window (screen). In your example, myFunciton will be invoked every time you click arrow left or arrow right.

I found you have used keycode instead of keyCode, that is the reason your myFunction doesn't be invoked. But 'keyCode' is deprecated. You should try like that :

window.addEventListener("keydown", (e) => {
    if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
      myFunction(e.key);
    }
});

function myFunction(key) {
  console.log("this is key", key);
}

Additionally, always used === operator for comparison in javascript.