Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
How to change the left position of div instance with arrow key using javascript?

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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
);

about 4 years ago · Juan Pablo Isaza Report

0

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 === 'ArrowRight') {
        event.target.dataset.shift = 'right'
    }
    if (event.key === 'ArrowLeft') {
        event.target.dataset.shift = 'default'
    }
})
.shift[data-shift='right'] {
    margin-left: 100px;
}
<input id="input_element" class="shift" data-shift="default" />

about 4 years ago · Juan Pablo Isaza Report

0

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
);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!