0

i need to increment the value top attribute of a div. for some reason it doesn't work.

i tried to use obj.style.top and increase the value but it doesn't work.

let sqr = document.getElementById("sqr")
let val = parseInt(sqr.style.top)
sqr.style.top = (val + 100) + "px";
body {
  width: 100vw;
  height: 100vh;
  position: relative;
}

#sqr {
  height: 30px;
  width: 30px;
  background-color: blue;
  position: absolute;
  top: 100px;
  left: 100px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Document</title>
  <link rel="stylesheet" href="index2.css" />
</head>

<body>
  <div id="sqr"></div>
  <script src="index2.js"></script>
</body>

</html>

I just want the square move up about 100 px. thanks.

Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
Shemesh
  • 39
  • 11

2 Answers2

0

Use

sqr.style.top= (sqr.offsetTop + 100) + "px";

style.top returns the top value set in style attribute on the html tag.

DevLasting
  • 352
  • 1
  • 9
0

The .style DOM property returns a CSS Style Declaration object containing the styles that have been set on the object through the HTML style attribute. Since your div doesn't have any inline styles applied to it, that technique won't return anything.

Instead, use getComputedStyle(), which returns the computed value of any/all styles, regardless of how/where they were set (inline, JavaScript, stylesheet).

Also (FYI):

As a best practice, you should always specify the optional second argument for parseInt() (the radix) to ensure you don't accidentally get a value you didn't expect.

let sqr = document.getElementById("sqr")
let val = parseInt(getComputedStyle(sqr).top, 10);
sqr.style.top= (val + 100) + "px";
body{
    width:100vw;
    height:100vh;
    position: relative;
}
#sqr{
    height: 30px;
    width:30px;
    background-color: blue;
    position:absolute;
    top:100px;
    left:100px;
}
<div id = "sqr"></div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71