Search code examples
javascriptimagedynamicpositiontrigonometry

Need help fixing Dynamic Position of Image JS


I have been working on a JS project where a sun goes around an image in a circle, and based on its position a higher index div will change opacity to make it darker or lighter. My problem is; while at one point the Sun moved in a circle, it no longer does. I have tried many things to fix this, but to no avail. My documented code is as follows:

<style>
  sun{
    position: absolute;
    z-index: 1;
  }
  dark-light{
    z-index: 2;
  }

</style>

CSS:^ JS:v

<script>



  move();

  //calls move


  function move(){
   //set rot
    var rot = 180;

    var pictureToDisplay = prompt('Please insert link to picture to     display','URL Necessary to function properly, but not required. Press enter to continue.');
    //asks user to insert picture link for STATIONARY picture
    var img = document.getElementById('img');

    if (pictureToDisplay == 'URL Necessary to function properly, but not required. Press enter to continue.'){

    }else{
    img.src = pictureToDisplay;
    }
    //Sets stationary picture
    window.setInterval( function() {

      //Repeats every 75 milliseconds forever.

      var obj = document.getElementById('sun');
    // obj. is equal to id sun
      var top = (Math.sin(rot)*500)+500;
      var left = (Math.cos(rot)*500)+500;
      //uses var rot, sine, and cosine to determine moving sun position
      var toppx = top + 'px';
      var leftpx = left + 'px';
      //adds the px after those values
      obj.style.top = toppx;
      obj.style.left = leftpx;
      //attempts to set position of obj (id sun)
      var darkToLight = -0.5+(top/500);
      //determines opacity of div using var top

      //document.write(rot+' = rot : ');

      var lightDiv = document.getElementById('dark-light');
      // same as var obj, but with the div
      lightDiv.style.opacity = darkToLight;
      //sets lightDiv to opacity
      //document.write(toppx,' ,',leftpx,' : ');


    rot = (rot+0.01) % 360;
      //moves rot up by 0.01, modulate 360
    }, 75);
    //back to top of setInterval
  }


</script>

P.S. I know no JQuery. Edit: The position of all is absolute, 0,0 is the top left corner of the page. I made sure not to deal with negatives. The sun should be absolute to the page, as its in nothing.


Solution

  • Ok, I figured out that I apparently am not too good with css, and after adding in style="position:absolute"; it now works fine.