0

I need to create a screen saver which has 2 images. One image should be static fixed which should occupy whole screen and second image should be moving on top of first one. I coded as below.

var bdg_img = document.getElementById('bdgimg');
var animate;
function moveRight()
{
  bdg_img.style.left = parseInt(bdg_img.style.left) + 10 + 'px';
  animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
moveRight();
html, body {
  position: relative;
  height: 100%;
  width: 100%
}
#bgimg {
    background-image: url("background/moon_bg.png");
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
    width: 100%;
    height: 100%;
}
#bdgimg {
    background-image: url("buildings/bdg6.png");
    position: absolute;
    background-color:transparent;
    bottom: 0px;
    left : 0px;
    width: 100%;
    height: 100%;
    border: 1px solid black;
}
<div id="bgimg">
</div>
<div id="bdgimg">
</div>

Even though moveRight() function is getting called continuously, 'bdgimg' div is not moving. Can anyone please let me know how to fix this.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
kadina
  • 5,042
  • 4
  • 42
  • 83
  • You have not define you css animation property yet – Friday Ameh Apr 10 '18 at 16:30
  • @FridayAmeh: The OP is updating the `left` of the element, not using CSS animations. – T.J. Crowder Apr 10 '18 at 16:32
  • Try `bdg_img.offsetLeft` instead of `bdg_img.style.left`. – Dong Nguyen Apr 10 '18 at 16:36
  • You'll want to get familiar with the debugger built into your browser. If you step through this with the debugger, you'll see that you're repeatedly assigning `NaNpx` to `left`. That's because `bdgimg.style.left` has no initial value. To get the value you're assigning via CSS, you need to get the *computed* `left` value. See the linked question's answers. – T.J. Crowder Apr 10 '18 at 16:37
  • `element.style.left` only works with inline styles, so you can't use it like that. You can get the `left` property like this: `var leftText = window.getComputedStyle(bdg_img, null).getPropertyValue('left');` [jsfiddle](https://jsfiddle.net/kra94c2u/10/) – Timovski Apr 10 '18 at 16:48
  • This works: https://jsfiddle.net/tef92frp/8/ You need to set the style left in JS first. That's the easiest way. You should also make it smoother using `requestAnimationFrame`: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame – SamMorrowDrums Apr 10 '18 at 16:50
  • Thanks @SamMorrowDrums. It is working. – kadina Apr 10 '18 at 17:20

0 Answers0