Friday, June 29, 2012

Moving DIV with Javascript

Dynamic HTML has always fascinated me. The first time I visited Dynamic Drive the hook was set. I have written many scripts with moving, growing, and bouncing DIVs. Many news tickers use this technique to scroll links and text. The following is an example of how to do it. All you need is a plain text editor, but an editor like Dreamweaver or Aptana will work nicely.

First, you need to create a web page with a DIV. Type or copy the code below into a text editor and save it as "mover.htm":

<html> <head> <title>Moving DIV</title> </head> <body> <div></div> </body></html>

Next, we need to edit the DIV tag and give it a few attributes. To start with, it needs an id attribute. This will be the name that will allow the script to find it. Next, we have to give it some style information to set some parameters like size, position, background color, etc. To do moving or floating layers position HAS to be set to absolute. For this example I am setting height at 75px, width at 100px, dropping it down 16px from the top of the browser window, setting the visibility to visible, and setting the background color to black:

<div id='target' style='position:absolute;height:175px;width:100px;top:160px;left:10px;visibility:visible;background-color:#000000;'></div>

Now it's time for the script. This script will placed under the DIV, since javascript can't "see" HTML containers until they are loaded. This is where the magic happens. The DIV 'target" is called and given the variable name "box". By using css we can dynamically set the left position of the DIV by calling parseInt(box.style.left)-1 and setting a timeout using setTimeout(scrollRight()",20) to control the interval (or speed) of the DIV's travel. By calling window.onload we can load the "scrollRight()" function when the content is loaded in the window:

<script language="Javascript" type="text/javascript"> <!-- var box=document.getElementById("target"); function scrollRight(){ box.style.top = 16; box.style.left=parseInt(box.style.left)+1; setTimeout("scrollRight()",20); } window.onload=scrollRight; //--> </script>

Save your work and open it up in a browser. To stop the DIV you can use the setTimeout("scrollRight()",20) as a named variable, use an if statement limiting the count of the parseInt method and use clearTimeout() to stop the count:

function scrollRight(){ box.style.top = 16; box.style.left=parseInt(box.style.left)+1; var sto = setTimeout("scrollRight()",20); if (parseInt(box.style.left)==1200){ box.style.left=100; clearTimeout(sto);} }

Enjoy!

No comments:

Post a Comment