Home > OS >  How to change the left position of div instance with arrow key using javascript?
How to change the left position of div instance with arrow key using javascript?

Time:05-28

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.

CodePudding user response:

It doesn't do nothing, it just doesn't do what you intend.

square2.div.style.left is set to 50px which you are then concatenating with 100 'px' which results in 50px100px.

The longhand solution is to parse out the number every time by stripping off the px, converting the string to a number (to avoid concatenation) and then adding to it.

square2.div.style.left =  square2.div.style.left.replace('px', '')   100   "px"; 

But this is cumbersome at best. The simpler solution is to declare a left property and increment it in your listener.

class Square {
  constructor(length) {
    
    ...
    
    this.xPos = 50;
    this.div.style.left = this.xPos   "px";
    
    this.left = this.xPos; //<-- declare new left prop set to initial value
  }
}

window.addEventListener(
  "keydown",
  function (event) {
  
  ...
  
  case "ArrowRight":
        square2.left  = 100; // increment left prop 
        square2.div.style.left = square2.left   "px"; 

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";
    
    this.left = this.xPos;

  }
}

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":
        // Do something for "left arrow" key press.
        break;

      case "ArrowRight":
        square2.left  = 100;
        square2.div.style.left = square2.left   "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
);

CodePudding user response:

IMO the best way to handle visual state changes in html using vanilla js is to actually use vanilla CSS. It's less code. It's cleaner. It's easier to support for other devs down the line.

  1. Add a data attribute to the html element
  2. Add a css class to the attribute
  3. Add eventlistener for the arrow down key to exectute.
  4. You can do this for any element...input, div etc...

input_element.addEventListener('keyup', (event) => {
    if (event.key === 'ArrowUp') {
        event.target.dataset.shift = 'right'
    }
    if (event.key === 'ArrowDown') {
        event.target.dataset.shift = 'default'
    }
})
.shift[data-shift='right'] {
    margin-left: 100px;
}
<input id="input_element"  data-shift="default" />

CodePudding user response:

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
   // }
    
    console.log(event.key)

    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.marginLeft  = 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
);

  • Related