moving an element in JS

To move an element by changing it’s top value, the element can’t have a static position (the default). You’ll need to change the position to absoluterelativefixed, etc….

Get the current topleft, etc… using Element#getBoundingClientRect, which will give you the correct initial value, and save you the need to parse a string. Since top needs to have a unit (px, em, etc..), add px to the changed top.

const myBox = document.querySelector("h1");
document.addEventListener('keydown', function(event) {
  if (event.keyCode == '38') {
    myBox.style.top = myBox.getBoundingClientRect().top - 5 + 'px'; // parse the string to number, subtract 5, and add 'px'
    console.log(myBox.style.top);
  }
});
h1 {
  position: absolute;
  top: 0;
  left: 0;
  width: 200px;
  height: 40px;
  border: 5px solid #BADA55;
  color: #A28;
  margin: 0;
  text-align: center;
}
<div>
  <h1>My text</h1>
</div>

Leave a Comment