Monday, May 20, 2024
12
rated 0 times [  16] [ 4]  / answers: 1 / hits: 17142  / 7 Years ago, sun, june 18, 2017, 12:00:00

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


More From » addeventlistener

 Answers
73

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>




[#57399] Friday, June 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dequant

Total Points: 88
Total Questions: 99
Total Answers: 95

Location: Ukraine
Member since Sun, Dec 13, 2020
4 Years ago
dequant questions
;