Javascript DOM Element move in animation

Description

Javascript DOM Element move in animation

View in separate window

  <!DOCTYPE html> 

  <html lang="en"> 
  <head> 
      <style> 
          #divAdvert { //from   w w  w .  j  av a 2s  . com
              position: absolute; 
              font: 12px Arial; 
              top: 4px; 
              left: 0px; 
          } 
      </style> 
  </head> 
  <body> 
      <div id="divAdvert"> 
          Here is an advertisement. 
      </div> 

      <script> 
          let switchDirection = false; 

          function doAnimation() { 
              let divAdvert = document.getElementById("divAdvert"); 
              let currentLeft = divAdvert.offsetLeft; 
              let newLocation; 

              if (!switchDirection) { 
                  newLocation = currentLeft + 2; 

                  if (currentLeft >= 400) { 
                      switchDirection = true; 
                  } 
              } else { 
                  newLocation = currentLeft - 2; 

                  if (currentLeft <= 0) { 
                      switchDirection = false; 
                  } 
              } 
            divAdvert.style.left = newLocation + "px"; 
        } 

        setInterval(doAnimation, 10); 
    </script> 

</body> 
</html> 

This page moves an element across the page from right to left.




PreviousNext

Related