1

I'm learning javascript and trying to make a simple exercise : I have a text box and want control it with keyboard. My HTML is the following (for now, I'm just trying 1 direction)

const myBox = document.querySelector("h1");
document.addEventListener('keydown', function (event){
    if (event.keyCode == '38'){
        myBox.style.top -= 5;
        console.log("test if it works");
    }
});

and my HTML is

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Tuto</title>

    <style>
        h1 {
            width: 200px;
            height: 40px;
            border: 5px solid #BADA55;
            color: #A28;
            margin: 0;
            text-align: center;
        }
    </style>
</head>
<body>

    <div><h1>My text</h1></div>

    <script type="text/javascript" src="main.js"></script>
</body>
</html>

My check test with console log works. So event listener does. But my box doesn't move. How can I solve it and why my use of .style.top is incorrect ?

Thank you

droledenom
  • 207
  • 2
  • 6
  • 18
  • How about adding `myBox.style.position = "absolute";` right before the line where you move the box? – geokavel Jun 18 '17 at 17:18
  • 1
    _"The [`HTMLElement.style`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) property is used to get as well as set the **inline style of an element**. While getting, it returns a `CSSStyleDeclaration` object that contains a list of all styles properties for that element with values assigned for the attributes that are **defined in the element's inline style attribute**."_ – Andreas Jun 18 '17 at 17:19
  • In this case, setting the position as "absolute' will mess up the element's initial position. I think you should use 'relative' instead. – Renan Souza Jun 18 '17 at 17:21

4 Answers4

1

Positions property like "top", "bottom", "left" and "right" will not work unless your element has the property "position" as "absolute" or "relative". In that case, what you want is to add "position: relative" to your h1 style on css.

If you want to understand more about that, this can give you a headstart https://www.w3schools.com/css/css_positioning.asp :D

Renan Souza
  • 905
  • 9
  • 25
0

1- you have to use let not const, because you want to change it and it is not fix;

let myBox = document.querySelector("h1");

2- you have to set your element as absolute position. because top property work not in static position

position:absolute;

3- you have to convert value of top position to number and then do something

myBox.style.top = parseFloat(myBox.style.top || 0) - 5 + 'px'; 

see my code : https://codepen.io/miladfm/pen/dRNLvw

miladfm
  • 1,508
  • 12
  • 20
0

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>

(reply) now we just need a way to prevent it from going out of bounds. think you can do that?

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 19 '23 at 23:09
-1

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 absolute, relative, fixed, etc....

Get the current top, left, 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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Ok thanks, in (parseFloat(myBox.style.top || 0) - 5 + 'px'), why do you use "| 0" ? – droledenom Jun 18 '17 at 20:05
  • The 1st time `top` is not set, so we need a default 0. However, I didn't like it, so I've changed it to `Element.getBoundingClientRect()`, which gets the initial value correctly, and parses the number. See edited answer. – Ori Drori Jun 18 '17 at 20:16