<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Design, Development, and Consulting &#187; Javascript</title>
	<atom:link href="http://netlumination.com/blog/category/tutorials/javascript/feed" rel="self" type="application/rss+xml" />
	<link>http://netlumination.com</link>
	<description>A web design, development, and consulting firm based in Portland, Oregon helping small businesseses and individuals.</description>
	<lastBuildDate>Wed, 01 Sep 2010 23:27:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Visibility Toggling with jQuery</title>
		<link>http://netlumination.com/blog/visibility-toggling-with-jquery</link>
		<comments>http://netlumination.com/blog/visibility-toggling-with-jquery#comments</comments>
		<pubDate>Mon, 16 Aug 2010 22:10:18 +0000</pubDate>
		<dc:creator>Peter</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[toggling]]></category>
		<category><![CDATA[visibility]]></category>

		<guid isPermaLink="false">http://netlumination.com/?p=1361</guid>
		<description><![CDATA[User interface design often makes use of showing and hiding blocks of content. It focuses one&#8217;s attention to the right thing, and it&#8217;s fun to do with jQuery. I&#8217;ll show you how to toggle the visibility on a group of selected elements. I&#8217;ll build up from a simple case to the more complicated ultimate goal. [...]]]></description>
			<content:encoded><![CDATA[<p>User interface design often makes use of showing and hiding blocks of content. It focuses one&#8217;s attention to the right thing, and it&#8217;s fun to do with <a href="http://jquery.com/">jQuery</a>.</p>
<p>I&#8217;ll show you how to toggle the visibility on a group of selected elements. I&#8217;ll build up from a simple case to the more complicated ultimate goal.</p>
<p><span id="more-1361"></span></p>
<p>First, whenever you&#8217;re working with jQuery and Javascript, you should probably get your references ready. For online references there&#8217;s the<a href="http://docs.jquery.com/Main_Page"> jQuery documentation</a> (which is easier to search with Google than with the site search, I find) and the <a href="https://developer.mozilla.org/en/javascript">Mozilla Development Center Javascript reference</a> among others. A very nice site to test, store, and share your jQuery snippets is <a href="http://jsfiddle.net/">jsFiddle</a>.</p>
<p>Ok, let&#8217;s get started. First let&#8217;s toggle the visibility of an element with jQuery using <a href="http://api.jquery.com/toggle/">.toggle()</a>. Since we&#8217;re talking about user interfaces, we&#8217;ll probably trigger the toggle with an action, let&#8217;s say a <a href="http://api.jquery.com/click/">.click()</a>:</p>
<ol>
<li>
<pre>$(document).ready(function(){</pre>
</li>
<li>
<pre>      // Toggle the visibility of all divs when one is clicked.</pre>
</li>
<li>
<pre>    $("input").click(function() {</pre>
</li>
<li>
<pre>        $("div").toggle();</pre>
</li>
<li>
<pre>    });</pre>
</li>
<li>
<pre>});​​</pre>
</li>
</ol>
<p><a href="http://jsfiddle.net/QXZ7p/">jsFiddle example</a></p>
<p>The code above will toggle the visibility of all the divs on a page if an input button is pressed.  The way this works is that after the document is ready, an event handler is bound to all the &lt;input&gt; elements. The handler waits for the user to click it. If clicked jQuery selects all the divs on the page and reverses their visibility. If they were invisible they become visible and vica versa.</p>
<p>Well, this was just to give you a tast of .toggle(), since the above example is pretty crude. Usually you want more control over which divs appear and disappear. In fact, an often trick part of visibility toggling in jQuery is to make sure each toggling button is linked uniquely to one block of content. You also want to ensure that when a block of content appears, all the other similar blocks of content disappears.</p>
<p>I&#8217;ll show you two methods of making sure that each time only one block of content appears, while all the other blocks of content disappears. The first method will only work if all the content blocks are siblings in the DOM. This will often be the case, since we&#8217;ll usually be dealing with semantically related chunks of content. The second way will be a little trickier but more flexible.</p>
<p>But before we start discussing siblings, let&#8217;s make sure we can toggle one specific div with one particular button. There&#8217;s many ways of doing this. I&#8217;ll show you how to use individual but related ids for the buttons and the content divs. Each button will have a name like, &#8220;block-x&#8221; where &#8220;x&#8221; is a number, and it&#8217;ll have a corresponding content block with the id &#8220;block-x-content&#8221;. Now if we have 3 content blocks, we could write one functions to control each block, for a total of 3 functions, but it&#8217;s more convenient and maintainable to generalize. We&#8217;re going to use input buttons with class &#8220;.toggler&#8221; to toggle the divs. You, of course, don&#8217;t have to use buttons, you can use other divs, or images, or whatever your little heart desires. So, so far we have:</p>
<ol>
<li>
<pre>$(document).ready(function(){</pre>
</li>
<li>
<pre>      // Toggle the visibility of all divs when one is clicked.</pre>
</li>
<li>
<pre>    $("input.toggler").click(function() {</pre>
</li>
<li>
<pre>        $( "#" + $(this).attr("id") + "-content" ).toggle();</pre>
</li>
<li>
<pre>    });</pre>
</li>
<li>
<pre>});​</pre>
</li>
</ol>
<p><a href="http://jsfiddle.net/N4PDK/">jsFiddle example</a></p>
<p>The most complex part is the line with the toggle. The previous line simply binds an click event handler to all input elements with a &#8220;toggler&#8221; class. The function that is triggered in case of a click is an anonymous function that toggles one div. To see witch div gets toggled we&#8217;ll look more closely at &#8220;$(&#8220;#&#8221; + $(this).attr(&#8220;id&#8221;) + &#8220;-content&#8221; )&#8221; . The part inside the parentheses is simply a jQuery selector string. The string starts with a literal &#8220;#&#8221;, so we know that an element with a certain ID is getting toggled. The &#8220;#&#8221; is followed by the &#8220;ID&#8221; attribute of the element that was clicked. So far we have something like $(&#8220;#block-x&#8221;). This by itself would make the buttons disappear. But we know that each button has a corresponding content block. This block is selected by concatenating &#8220;-content&#8221; to the previous to give us a toggling of $(&#8220;#block-x-content&#8221;). Where is the number in the ID attribute of the INPUT button we clicked. Notice how the visibility of each DIV is kept track of separately. .toggle() is doing all the hard work for us.</p>
<p>Well, we&#8217;re approaching what we want. The previous example is okay, in that it let&#8217;s us toggle things, but it doesn&#8217;t really feel like we&#8217;re concentrating the attention of the user to one pertinent block of information. To achieve that end, we must make all the other divs invisible when we make one div visible.</p>
<p>We only have to change one line to achieve this. We&#8217;ll go from:</p>
<pre>$( "#" + $(this).attr("id") + "-content" ).toggle();</pre>
<p>to:</p>
<pre>$( "#" + $(this).attr("id") + "-content" ).toggle().siblings().hide();</pre>
<p>Notice how I chained the methods .siblings() and .hide() onto the previous line. This means that after toggling our content block, we&#8217;ll select the DOM siblings of that block and make them invisible. This means you have to make sure you&#8217;ve thought through your HTML. The easy way to do this is to nest all the content divs into a parent div, or if it makes sense, maybe to have content LIs in a parent UL or OL.</p>
<p>One finally change is that you may not want the content to disappear if a button is pressed twice, so we&#8217;ll switch out .toggle() with .show() to give:</p>
<ol>
<li>
<pre>$(document).ready(function(){</pre>
</li>
<li>
<pre>      // Toggle the visibility of all divs when one is clicked.</pre>
</li>
<li>
<pre>    $("input.toggler").click(function() {</pre>
</li>
<li>
<pre>        $( "#" + $(this).attr("id") + "-content" ).show().siblings().hide();</pre>
</li>
<li>
<pre>    });</pre>
</li>
<li>
<pre>});​</pre>
</li>
</ol>
<p><a href="http://jsfiddle.net/NeVDs/">jsFiddle example</a></p>
<p>But what if our content DIVs aren&#8217;t siblings? They usually should be, just because of the way information is structured on an HTML page, but we really don&#8217;t want to count on that. We want the flexibility to toggle any set of elements we want.</p>
<p>To toggle any set of elements we want, all we have to do is create jQuery set of the elements and use .not() in combination with that. I&#8217;ll show you how.</p>
<p>First, let&#8217;s say that we have 3 content divs. Let&#8217;s select all of them with jQuery:</p>
<pre>
var theDivs = $("#block-1-content, #block-2-content, #block-3-content);
</pre>
<p>So, now theDivs is a jQuery selection of out content DIVs, let&#8217;s use that in combination with our click handler and .not() to toggle the appropriate content divs. Except, now I&#8217;m going to use an unordered list, so our content will be in LIs. If we&#8217;re dealing with unordered lists, we could easy have a situation where all the individual content LIs are not siblings of each other.</p>
<p>To show the corresponding content LI of a button, we&#8217;ll still use:</p>
<pre>
$( "#" + $(this).attr("id") + "-content" ).show();
</pre>
<p>But now we can&#8217;t simply make the siblings disappear. Instead we&#8217;ll make everything from our jQuery slection &#8220;theDivs&#8221; that isn&#8217;t the corresponding content LI vanish. Like this:</p>
<pre>
theDivs.not( $( "#" + $(this).attr("id") + "-content" ) ).hide();
</pre>
<p>And that&#8217;s it! You can of course replace the .show() and .hide() methods with fancier animations like .slideDown() and .slideUp(), but overall we have a relatively simple to implement, generalizable way of toggling the visibility of a group of content divs. The full code will look something like this:</p>
<ol>
<li>
<pre>$(document).ready(function(){</pre>
</li>
<li>
<pre>      // Create a selection of the content divs of interest</pre>
</li>
<li>
<pre>    var theDivs = $("#block-1-content, #block-2-content, #block-3-content");</pre>
</li>
<li>
<pre>      // Toggle the visibility of all divs when one is clicked.</pre>
</li>
<li>
<pre>    $("input.toggler").click(function() {        </pre>
</li>
<li>
<pre>        $( "#" + $(this).attr("id") + "-content" ).show();</pre>
</li>
<li>
<pre>        theDivs.not( $( "#" + $(this).attr("id") + "-content" ) ).hide();</pre>
</li>
<li>
<pre>    });</pre>
</li>
<li>
<pre>});​</pre>
</li>
</ol>
<p><a href="http://jsfiddle.net/NNLzj/">jsFiddle example</a></p>
]]></content:encoded>
			<wfw:commentRss>http://netlumination.com/blog/visibility-toggling-with-jquery/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A few code snippets.</title>
		<link>http://netlumination.com/blog/a-few-code-snippets</link>
		<comments>http://netlumination.com/blog/a-few-code-snippets#comments</comments>
		<pubDate>Sun, 25 Jul 2010 02:40:09 +0000</pubDate>
		<dc:creator>Peter</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[samples]]></category>

		<guid isPermaLink="false">http://netlumination.com/?p=1325</guid>
		<description><![CDATA[I often write very short, very simply little code snippets just to test specific things in HTML, CSS, PHP, or Javascript (and jQuery).  These are short little blurbs, that are useful for looking at how certain specific things work. They are mostly notes to self. Here are links to a few of them: Short Code [...]]]></description>
			<content:encoded><![CDATA[<p>I often write very short, very simply little code snippets just to test specific things in HTML, CSS, PHP, or Javascript (and jQuery).  These are short little blurbs, that are useful for looking at how certain specific things work. They are mostly notes to self.</p>
<p>Here are links to a few of them:</p>
<table>
<tbody>
<tr>
<td colspan="2"><strong>Short Code Snippets:</strong></td>
</tr>
<tr>
<td>CSS</td>
<td><a href="http://peter-ajtai.com/examples/html/images.php">Change image on hover.</a></td>
</tr>
<tr>
<td>CSS</td>
<td><a href="http://peter-ajtai.com/examples/html/menu-good.html">Creating large clickable areas.</a></td>
</tr>
<tr>
<td>CSS</td>
<td><a href="http://peter-ajtai.com/examples/html/sample.html">Images sprites example</a> &#8211; <a href="http://peter-ajtai.com/examples/html/styles.css">External CSS is here</a> &#8211; <a href="http://peter-ajtai.com/examples/html/images/sprite.png">Sprite is here</a></td>
</tr>
<tr>
<td>DOM</td>
<td><a href="http://peter-ajtai.com/examples/html/dom.php">Checking how many elements in an ID.</a></td>
</tr>
<tr>
<td>Javascript</td>
<td><a href="http://peter-ajtai.com/examples/js/animation.php">Basketball animation</a></td>
</tr>
<tr>
<td>jQuery</td>
<td><a href="http://peter-ajtai.com/examples/js/custom-iteration.php">Return ID of clicked LI</a></td>
</tr>
<tr>
<td>jQuery</td>
<td><a href="http://peter-ajtai.com/examples/js/jq-exs.php">Sliding, fading, and disappearing</a></td>
</tr>
<tr>
<td>jQuery</td>
<td><a href="http://peter-ajtai.com/examples/js/not.php">Not this array element</a></td>
</tr>
<tr>
<td>jQuery</td>
<td><a href="http://peter-ajtai.com/examples/js/toggle.php">Using toggle()</a></td>
</tr>
<tr>
<td>PHP Algorithm</td>
<td><a href="http://peter-ajtai.com/examples/php/lll.php">A linear linked list</a></td>
</tr>
<tr>
<td>PHP Recursion</td>
<td><a href="http://peter-ajtai.com/examples/numbers.php">Turning digits into words</a></td>
</tr>
<tr>
<td>PHP JSON CSS</td>
<td><a href="http://peter-ajtai.com/examples/php/del.php">Retrieving and displaying information from Delicious</a></td>
</tr>
<tr>
<td colspan="2"><strong>Simple Apps:</strong></td>
</tr>
<tr>
<td>jQuery PHP</td>
<td><a href="http://peter-ajtai.com/examples/php/so.php">Guessing game using Stackapps and Stackoverflow data</a></td>
</tr>
<tr>
<td>jQuery PHP</td>
<td><a href="http://peter-ajtai.com/examples/js/highlight.php">Dynamic Syntax Highlighting</a></td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://netlumination.com/blog/a-few-code-snippets/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JQuery for a little night time reading</title>
		<link>http://netlumination.com/blog/jquery-for-a-little-night-time-reading</link>
		<comments>http://netlumination.com/blog/jquery-for-a-little-night-time-reading#comments</comments>
		<pubDate>Tue, 15 Jun 2010 01:16:26 +0000</pubDate>
		<dc:creator>Peter</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[source code]]></category>

		<guid isPermaLink="false">http://netlumination.com/?p=1242</guid>
		<description><![CDATA[If you use Javascript, JQuery is a great framework to speed up your coding. It&#8217;s essentially a collection of really convenient shortcuts. It does more, since JQuery also handles a lot of browser compatibility issues. So, you don&#8217;t have to go through your JQuery code to update it for new browsers, all you have to [...]]]></description>
			<content:encoded><![CDATA[<p>If you use Javascript, <a href="http://jquery.com/">JQuery</a> is a great framework to speed up your coding. It&#8217;s essentially a collection of really convenient shortcuts. It does more, since JQuery also handles a lot of browser compatibility issues. So, you don&#8217;t have to go through your JQuery code to update it for new browsers, all you have to do is download the new version of JQuery, and your old commands will learn new tricks.</p>
<p>Ah, speaking of downloading JQuery, you just might want to understand how JQuery works if you use it. The first time I tried to do this, I simply clicked on my JQuery src file link:</p>
<ol>
<li>
<pre>&lt;script type="text/javascript" src="http://peter-ajtai.com/jquery/jquery-1.4.2.min.js"&gt;&lt;/script&gt;</pre>
</li>
</ol>
<p>&#8230; and this is what I saw:</p>
<p><img class="alignnone size-full wp-image-1243" title="Happy reading" src="http://netlumination.com/wp-content/uploads/2010/06/wall-o-text.jpg" alt="Wall o text JQuery" width="419" height="323" /></p>
<p>Fun reading, huh? <span id="more-1242"></span>Well, when your browser loads Javascript, it has to load each charachter, so the less whitespace there is, and the shorter the variable names are, the faster it will load.</p>
<p>This means you should be using this, the minified, version of JQuery on your site, but if you want some <del>pleasant and relaxing</del> reading&#8230; you should look at the uncompressed version. <a href="http://docs.jquery.com/Downloading_jQuery">JQuery shows you both versions very clearly on their download page</a>, but for some reason, it took me a while to realize that there is an uncompressed version. The <a href="http://code.jquery.com/jquery-latest.js">uncompressed version of the latest version is here</a>. The uncompressed version is actually very readable:</p>
<p><img class="alignnone size-full wp-image-1244" title="That's better" src="http://netlumination.com/wp-content/uploads/2010/06/readable.jpg" alt="Readable JQuery" width="423" height="352" /></p>
]]></content:encoded>
			<wfw:commentRss>http://netlumination.com/blog/jquery-for-a-little-night-time-reading/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Simple Animations With Javascript</title>
		<link>http://netlumination.com/blog/creating-simple-animations-with-javascript</link>
		<comments>http://netlumination.com/blog/creating-simple-animations-with-javascript#comments</comments>
		<pubDate>Fri, 16 Oct 2009 04:49:21 +0000</pubDate>
		<dc:creator>Peter</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[timer]]></category>

		<guid isPermaLink="false">http://netlumination.com/?p=535</guid>
		<description><![CDATA[This is a basic JavaScript tutorial. I will describe how to move an element around the page using a simple animation script. The element you move around the page can be anything from an image to a paragraph. Below is a working example: // 200) { directionBall=-1; } if (0>distanceBall) { directionBall=1; } timerToggle=setTimeout(function() { [...]]]></description>
			<content:encoded><![CDATA[<p>This is a basic JavaScript tutorial. I will describe how to move an element around the page using a simple animation script. The element you move around the page can be anything from an image to a paragraph.</p>
<p>Below is a working example:</p>
<p><script type="text/javascript">// <![CDATA[
    var distanceBall=0; var directionBall=1; var timerToggle=null; function animateBall() {   document.getElementById("basketball").style.top=distanceBall + "px";   distanceBall+=directionBall;   if (distanceBall>200) { directionBall=-1; }
  if (0>distanceBall) { directionBall=1; }
  timerToggle=setTimeout(function() { animateBall(); },10);
}
function checkButton() {
  if (document.getElementById("ballButton").value=="Animate Basketball") {
    document.getElementById("ballButton").value="Stop Basketball";
    animateBall();
  } else {
    document.getElementById("ballButton").value="Animate Basketball";
    clearTimeout(timerToggle);
  }
}
// ]]&gt;</script></p>
<input id="ballButton" onclick="checkButton()" type="button" value="Animate Basketball" />
<div id="basketball" style="position: relative;"><img src="http://netlumination.com/wp-content/uploads/2009/10/Basketball_64x64-1.png" alt="Basketball" /></div>
<p><span id="more-535"></span></p>
<ol>
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Starting">Starting and stopping the animation using checkButton()</a></li>
<li><a href="#Moving">Moving the ball image using animateBall()</a></li>
<li><a href="#References">References</a></li>
<li><a href="#Conclusion">Conclusion</a></li>
</ol>
<h2><a name="Introduction"></a>Introduction</h2>
<p>Here is the code that makes the ball move. For the rest of this post, I&#8217;ll go over the basic ideas required to put the code together and how the specific code works:</p>
<ol>
<li>
<pre>&lt;script type="text/javascript"&gt;</pre>
</li>
<li>
<pre>// &lt;!--</pre>
</li>
<li>
<pre>    var distanceBall=0; </pre>
</li>
<li>
<pre>    var directionBall=1; </pre>
</li>
<li>
<pre>    var timerToggle=null; </pre>
</li>
<li>
<pre>    </pre>
</li>
<li>
<pre>    function animateBall() {   </pre>
</li>
<li>
<pre>        document.getElementById("basketball").style.top=distanceBall + "px";</pre>
</li>
<li>
<pre>        distanceBall+=directionBall;</pre>
</li>
<li>
<pre>        if (distanceBall&gt;200) { directionBall=-1; }</pre>
</li>
<li>
<pre>        if (0&gt;distanceBall) { directionBall=1; }</pre>
</li>
<li>
<pre>        timerToggle=setTimeout(function() { animateBall(); },10);</pre>
</li>
<li>
<pre>    }</pre>
</li>
<li>
<pre>    </pre>
</li>
<li>
<pre>    function checkButton() {</pre>
</li>
<li>
<pre>        if (document.getElementById("ballButton").value=="Animate Basketball") {</pre>
</li>
<li>
<pre>            document.getElementById("ballButton").value="Stop Basketball";</pre>
</li>
<li>
<pre>            animateBall();</pre>
</li>
<li>
<pre>        } else {</pre>
</li>
<li>
<pre>            document.getElementById("ballButton").value="Animate Basketball";</pre>
</li>
<li>
<pre>            clearTimeout(timerToggle);</pre>
</li>
<li>
<pre>        }</pre>
</li>
<li>
<pre>    }</pre>
</li>
<li>
<pre>// --&gt;</pre>
</li>
<li>
<pre>&lt;/script&gt;</pre>
</li>
<li>
<pre></pre>
</li>
<li>
<pre>&lt;input id="ballButton" onclick="checkButton()" type="button" value="Animate Basketball" /&gt;</pre>
</li>
<li>
<pre>&lt;div id="basketball" style="position: relative;"&gt;</pre>
</li>
<li>
<pre>    &lt;img src="http://netlumination.com/wp-content/uploads/2009/10/Basketball_64x64-1.png" alt="Basketball" /&gt;</pre>
</li>
<li>
<pre>&lt;/div&gt;</pre>
</li>
</ol>
<p><a href="http://jsfiddle.net/g3x9f/">Here&#8217;s a jsFiddle for you to play with.</a></p>
<p>There are two functions in this script, animateBall() and checkButton(). animateBall() is what makes the basketball image move. checkButton() starts and stops the ball. Let&#8217;s start by going over checkButton(), since that is the function that is called if the viewer presses the &#8220;Animate Basketball&#8221; button.</p>
<p><script type="text/javascript">// <![CDATA[
    google_ad_client = "pub-4166122661117213"; /* 336x280, created 4/27/09 */ google_ad_slot = "9673694336"; google_ad_width = 336; google_ad_height = 280;
// ]]&gt;</script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript">
</script></p>
<h2><a name="Starting"></a>Starting and stopping the animation using checkButton()</h2>
<p>Whenever you create an animation, or any sort of constantly running JavaScript, it&#8217;s considerate to allow the viewer to stop the script somehow. This is done using the checkButton function. The checkButton function also starts the script running, so it serves a dual purpose.</p>
<ol>
<li>
<pre>function checkButton()</pre>
</li>
<li>
<pre>{</pre>
</li>
<li>
<pre>  if (document.getElementById(“ballButton”).value == ”Animate Basketball”) </pre>
</li>
<li>
<pre>  {    </pre>
</li>
<li>
<pre>    document.getElementById(“ballButton”).value = ”Stop Basketball”;</pre>
</li>
<li>
<pre>    animateBall();</pre>
</li>
<li>
<pre>  } else </pre>
</li>
<li>
<pre>  {</pre>
</li>
<li>
<pre>    document.getElementById(“ballButton”).value = ”Animate Basketball”;</pre>
</li>
<li>
<pre>    clearTimeout(timerToggle);</pre>
</li>
<li>
<pre>  }</pre>
</li>
<li>
<pre>}</pre>
</li>
</ol>
<p>The checkButton function checks what the input button says and does  one of two things based upon what the button reads. Looking at the HTML of the INPUT button, you can see that the INPUT button has the ID of &#8220;ballButton.&#8221; So, we can use document.getElementById(”ballButton”).value to access the words on the button. Accessing  HTML elements, their attributes, and inline CSS styles on a web page with Javascript can be done using the Document Object Model (DOM). <a href="http://www.javascriptkit.com/domref/">Here</a> and <a href="http://www.w3schools.com/jsref/default.asp">here</a> are two easy to use references for the DOM.</p>
<p>checkButton() first replaces the words in the button. If the button reads, &#8220;Animate Basketball&#8221; it writes in &#8220;Stop Basketball&#8221; instead. We know the button can only read one of two things, so we use the <a href="http://www.w3schools.com/js/js_if_else.asp">ELSE statement</a> to set the INPUT BUTTON to &#8220;Animate Basketball&#8221; if it doesn&#8217;t already say that. So one of the things the IF, ELSE statement does is toggle the INPUT BUTTON between &#8220;Animate Basketball&#8221; and &#8220;Stop Basketball&#8221;</p>
<p>There is a second line after the writing on the button is changed. If the button read &#8220;Animate Basketball&#8221; then the function animateBall is called. This gets the ball moving.</p>
<p>If the button read &#8220;Stop Basketball,&#8221; the ELSE statement, then the ball is stopped using clearTimeout. I&#8217;ll go over how clearTimeout works later. For now it&#8217;s just important to understand that checkButton simply functions as a toggle that does two things whenever it&#8217;s called. First, it changes the writing on the INPUT button. Second, it either starts or stops the basketball image moving.</p>
<p>Let&#8217;s look at how the basketball image is moved when checkButton() calls the animateBall function.</p>
<h2><a name="Moving"></a>Moving the ball image using animateBall()</h2>
<p>This is the heart of the animation, and what&#8217;s startling is how few lines it takes to animate something with JavaScript.</p>
<p>Essentially what we want to do is move the DIV containing the basketball image small steps at a time. This requires two things: physical movement of the DIV and a time increment in which this movement will be done.</p>
<ol>
<li>
<pre>var distanceBall=0; </pre>
</li>
<li>
<pre>var directionBall=1; </pre>
</li>
<li>
<pre>var timerToggle=null; </pre>
</li>
<li>
<pre></pre>
</li>
<li>
<pre>function animateBall() {   </pre>
</li>
<li>
<pre>    document.getElementById("basketball").style.top=distanceBall + "px";</pre>
</li>
<li>
<pre>    distanceBall+=directionBall;</pre>
</li>
<li>
<pre>    if (distanceBall&gt;200) { directionBall=-1; }</pre>
</li>
<li>
<pre>    if (0&gt;distanceBall) { directionBall=1; }</pre>
</li>
<li>
<pre>    timerToggle=setTimeout(function() { animateBall(); },10);</pre>
</li>
<li>
<pre>}</pre>
</li>
<li>
<pre></pre>
</li>
</ol>
<p>If you look at the HTML, you&#8217;ll see that the basketball image is in a div with the ID &#8220;basketball&#8221; and the it&#8217;s CSS style of postion is set to RELATIVE. It&#8217;s important to set the position to RELATIVE, since that means that we can use the TOP or LEFT CSS styles to change the position of the DIV relative to where you see it when the image loads.</p>
<ol>
<li>
<pre>&lt;div id="basketball" style="position: relative;"&gt;</pre>
</li>
<li>
<pre>    &lt;img src="http://netlumination.com/wp-content/uploads/2009/10/Basketball_64x64-1.png" alt="Basketball" /&gt;</pre>
</li>
<li>
<pre>&lt;/div&gt;</pre>
</li>
</ol>
<p>There are three variables that the animateBall function uses. The first is distanceBall. distanceBall is how many pixels the TOP CSS property of the DIV with the basketball image in it is set to. So distanceBall will control where the image is displayed. directionBall will control whether the image is moving up or down. We need this so that the image doesn&#8217;t wander too far away. Finally the timerToggle variable will allow us to stop the ball from moving. This is done as a courtesy to the viewer.</p>
<p>The first line of the animateBall function adds directionBall to distanceBall. Initially directionBall is 1, so this simply adds 1 to distanceBall.</p>
<p>Next we display the DIV containing the basketball image at this new location. We use the HTML DOM objects to reference the DIV. We know the DIV has an ID of &#8220;basketball&#8221;. This makes it easy to pick out from all the other elements on the page by writing document.getElementById(&#8220;basketball&#8221;). Now to specifically target the CSS TOP style we&#8217;ll use document.getElementById(&#8220;basketball&#8221;).style.top. The top property can be read from the browser or it can be written to. In other words we can change it. It&#8217;s almost as simple as setting it equal to distanceBall. The only trick part is that TOP has units. We&#8217;ll use pixels, so me must concatenate &#8220;px&#8221; to the end of the number. We do this using the + <a href="http://jennifermadden.com/javascript/concatenation.html">string operator</a>.</p>
<p>So with just two lines of code we&#8217;ve moved the DIV one pixel. The next two lines, the two if statements, check if the DIV is at a TOP greater than 200 or less than 0. If it is, it reverses the direction of movement, so that the ball ends up bouncing up and down 200 pixels. Here is an alternative way to write those two lines as one line (to understand the codes look at this page on <a href="http://www.w3schools.com/JS/js_comparisons.asp">JavaScript comparison and logical operators</a>):</p>
<ol>
<li>
<pre>if(distanceBall&gt;200 || distanceBall&lt;0){directionBall*=-1;}</pre>
</li>
</ol>
<p>Anyway, this all looks great so far, but we&#8217;ve only moved the ball one pixel. We have to repeat this movement every few moments. This would be very easy if there was a function to pause a JavaScript program, but there isn&#8217;t, and trying to make a custom function to do this can end up with very messy results. There is, however, a way to tell JavaScript to do an action in a set amount of time. It&#8217;s like setting an alarm clock. It&#8217;s called setTimeout() and here is how it works:</p>
<ol>
<li>
<pre>setTimeout( [What to do] , [How long to wait] );</pre>
</li>
</ol>
<p>It&#8217;s important to realize that when you use setTimeout(), Javascript will keep evaluating the lines below setTimeout immediately. It does not pause. It&#8217;s like setting an alarm and keeping right on going, now with the alarm timer ticking in the background.</p>
<p>The way to use setTimeout in our animation function is to use it as the last line, and have it call our animation function itself. Like this:</p>
<ol>
<li>
<pre>function animateBall() {</pre>
</li>
<li>
<pre>    [ move ball one increment and show it at its new location ]</pre>
</li>
<li>
<pre>    setTimeout( function() { animateBall(); } , 10 );</pre>
</li>
<li>
<pre>}</pre>
</li>
</ol>
<p>This will perform the animateBall() function once every 10 milliseconds, since setTimeout measures time in milliseconds. It&#8217;s important that animateBall is not a for, while, or do loop, since setTimeout does not pause the execution of the script. Also, not the use of the anonymous function ( function () { &#8230; } ) in setTimeout. This is better than putting animateBall() in quotes and using eval().</p>
<p>Now that we have the ball going, how can we make it stop? The way to stop the animation and the ball is to somehow get setTimeout() to stop firing.</p>
<p>You&#8217;ll notice that the variable timerToggle is set equal to setTimeout() in the animateBall funciton. This may look confusing, since it&#8217;s not immediately apparent what sort of variable timerToggle is. Well, timerToggle simply allows us to keep track of the specific timer we used for the animation, so that we can stop it by using clearTimeout().</p>
<p>To stop a timer we&#8217;ll use clearTimeout(). The only thing we have to do is tell the browser which timer we want to stop. Luckily this is what the timerToggle variable is for, so clearTimeout(timerToggle) will stop the ball from moving.</p>
<p>clearTimeout() is not in the animateBall function, it is in the checkButton function. This is because clearTimeout is called if the viewer presses the button while the ball is moving.</p>
<p><script type="text/javascript">// <![CDATA[
    google_ad_client = "pub-4166122661117213"; /* 336x280, created 4/27/09 */ google_ad_slot = "9673694336"; google_ad_width = 336; google_ad_height = 280;
// ]]&gt;</script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript">
</script></p>
<h2><a name="Conclusion"></a>Conclusion</h2>
<p>Ok, so that&#8217;s it. You can animate a DIV on your page using one simple function, and you can stop and start the animation using a second function.</p>
<p>Remember that we are moving the DIV with the image inside. This means we could also put other things in the DIV like a paragraph, form, list, etc.</p>
<p>You should always consider the pros and cons of using animations on your page. As anyone who has sat through a few Power Point presentation knows, it is easy to go overboard with animations (and sound effects, but that&#8217;s another matter).</p>
<p>However, if you can link the animation to the content of your page, it may be well worth using it. For example, if you have a site about food, you could style the logo of your page to slide onto the page like a platter of food being served. Again, this can be done elegantly or it can be easily overdone. Additionally animation and interactivity (like the ability to start and stop the animation) is the seed of video games and interactive art.</p>
<p>Finally, you should consider how this simple function can be improved. You might have noticed that I used global variables. This limits the names of other variables that can be used on the same page, which can be especially problematic or confusing in large projects. So, removing the global variables would be ideal. This leads me to a second possible change. Instead of using an inline call to a javascript function in an HTML DIV, I could create an event handler for that DIV. This would allow me to get rid of the global variables too.</p>
<p>Exactly how to do that might be the subject for a later post.</p>
<h2><a name="References"></a>References</h2>
<p><a href="http://www.chipchapin.com/WebTools/JavaScript/exampleA01.html">Tutorial on JavaScript animation</a></p>
<p><a href="http://www.w3schools.com/jS/js_operators.asp">Javascript operators</a></p>
<p><a href="http://www.java2s.com/Code/JavaScriptReference/Javascript-Methods/CatalogJavascript-Methods.htm">Javascript methods</a></p>
<p><a href="http://www.javascriptkit.com/domref/index.shtml">Javascript DOM reference</a></p>
<p><a href="http://www.w3schools.com/jsref/default.asp">Javascript DOM reference</a></p>
<p><a href="http://www.iconspedia.com/icon/basketball-ball-438-.html">Basketball Image</a></p>
]]></content:encoded>
			<wfw:commentRss>http://netlumination.com/blog/creating-simple-animations-with-javascript/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
