Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    May 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How to Do Simple Movement in Javascript?

    I have a simple box created with a div. What is the simplest way to make that box move to the left one pixel at a time, a total of 20 pixels?

    Code:
    <html>
    
    <div id='box' style='background-color:#aadd22; width:20px; height:20px'></div>
    
    </html>
    I assume you would have to use a setTimeOut?

  • #2
    New Coder
    Join Date
    May 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Also, I need it to work in IE8. I have tried using the style.left, but it doesn't seem to work.

  • #3
    New Coder
    Join Date
    May 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I'm sorry, I meant, move it 20 pixels to the right.

    Where is the edit button on the posts?

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    You can't edit your posts until you've accumulated a certain number. 50 I think, but check the Announement at the top of the forum listings.

    Like this?
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>demo</title>
    <style type="text/css">
    #box {
        position: absolute;
        display: block;
        left: 100px; top: 100px;
        width: 20px; height: 20px;
        background-color: #aadd22; 
        border: solid green 2px;
    }
    </style>
    </head>
    <body>
    
    <div id="box"></div>
    
    <script type = "text/javascript">
    (
      function( )
      {
          var mybox = document.getElementById("box");
          var boxleft = 100;
          
          function movebox( )
          {
              if ( boxleft >= 120 ) return; // done
              ++boxleft;
              mybox.style.left = boxleft + "px";
              setTimeout( movebox, 100 );
          }
          movebox( );
      }
    )();
    </script>
    
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New Coder
    Join Date
    May 2011
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts
    thank you!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •