0

CSS:

 <style>
#container {
  width: 200px;
  height: 200px;
  background: green;
  position: relative;

}
#box {
  width: 50px;
  height: 50px;
  background: red;
  position: absolute;
}
</style>
<div id="container">
   <div id="box"> </div>
</div>

JavaScript:

var pos = 0; 
var box = document.getElementById("box");
function move() {
  pos += 1;
  box.style.left = pos+"px"
}

If I just use box.style.left = "150px" the red box will be right in the corner of the green box but if I use box.style.left = pos+"50px" the same happens and I don't know why? I don't understand why even declare the variable pos in the first place.

  • What uses the move function? I'm guessing this is something that moves the element 1 pixel at a time. This is a good example of why putting comments in your code is necessary. – Doug F Feb 17 '19 at 19:20
  • Is that all the JS code you have? It would seem that `move()` is to move the box across the screen over time. – Keno Feb 17 '19 at 19:21
  • https://codepen.io/nagasai/pen/QYzEEp, pos is used to move the box from left to right by px specified in pos + 1 – Naga Sai A Feb 17 '19 at 19:24

2 Answers2

0

That is shorthand for pos = pos +1;

It's then being used to style the div with the id of box 1 pixel to the right, based on the left margin, so it will nudge right across page.

You'd need some sort of click handler associated to a button in the HTML markup to call move to make something happen.

JGFMK
  • 8,425
  • 4
  • 58
  • 92
0

pos + '50px' is 150px , as number plus string , will be concatenated string as mentioned below

pos = 0

pos += 1 //pos = 0 + 1 = 1

pos = 1 + '50px' // 150px ,as string it concatenates to 150px

codepen = https://codepen.io/nagasai/pen/QYzEEp

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40