<?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>dougv.com « Doug Vanderweide &#187; DOM images</title>
	<atom:link href="http://www.dougv.com/tag/dom-images/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.dougv.com</link>
	<description>ASP.NET, PHP, XML, JavaScript, Web geekery, Entrepreneurship</description>
	<lastBuildDate>Thu, 17 May 2012 22:33:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Preloading Images With JavaScript</title>
		<link>https://www.dougv.com/2012/03/12/preloading-images-with-javascript/</link>
		<comments>https://www.dougv.com/2012/03/12/preloading-images-with-javascript/#comments</comments>
		<pubDate>Mon, 12 Mar 2012 23:10:43 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[coding standards]]></category>
		<category><![CDATA[DOM images]]></category>
		<category><![CDATA[elegance]]></category>

		<guid isPermaLink="false">http://www.dougv.com/?p=4491</guid>
		<description><![CDATA[In my recent travels through old blog posts, I&#8217;ve noticed a number of occasions where I&#8217;ve discussed how to preload images. Almost all those examples are stupid or just plain wrong. For that, you have my apologies, and I aim to rectify those mistakes with this post. First, why would we want to preload an [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/04/04/displaying-static-random-html-and-images-on-a-web-page-via-ajax/" rel="bookmark">Displaying Static, Random HTML And Images On A Web Page Via AJAX</a> (17)</li>
				<li><a href="https://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/" rel="bookmark">Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM</a> (15.6)</li>
				<li><a href="https://www.dougv.com/2009/06/14/the-simplest-ways-to-do-image-rollover-effects-javascript-and-css-only/" rel="bookmark">The Simplest Ways To Do Image Rollover Effects: JavaScript And CSS-Only</a> (15.4)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_4494" class="wp-caption alignright" style="width: 210px"><img src="/wp-content/uploads/2012/03/anne+hathaway-Hot-Sexy-Gallery-Photos5.jpg" alt="anne+hathaway" title="anne+hathaway" width="200" height="302" class="size-full wp-image-4494" /><p class="wp-caption-text">Anne Hathaway</p></div>In my recent travels through old blog posts, I&#8217;ve noticed a number of occasions where I&#8217;ve discussed how to <a href="/tag/dom-images/">preload images</a>.</p>
<p>Almost all those examples are stupid or just plain wrong. For that, you have my apologies, and I aim to rectify those mistakes with this post.</p>
<p>First, why would we want to preload an image? Simply put, we intend to show it later on our Web page &#8212; either as a result of a mouseover, or a click, or some other sort of Document Object Model (<a href="http://www.w3schools.com/htmldom/default.asp">DOM</a>) event. </p>
<p>For example, maybe we want to <a href="http://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/" title="Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM">mouseover a series of thumbnails, and show a larger version of that image in the same place</a>.</p>
<p>Rather than making the end user wait for a new image to load as a result of doing something on a Web page, it makes sense to load the image we intend to show in advance, so it will display almost instantaneously as a result of an event.</p>
<p>I&#8217;ll first show why two of my previous methods for preloading images are wrong or dumb, then describe two correct ways to preload images: via basic JavaScript and via <a href="http://jquery.com/" target="_blank">jQuery</a>. </p>
<p>The lovely <a href="http://www.imdb.com/name/nm0004266/" target="_blank">Anne Hathaway</a> will be our model.<br />
<span id="more-4491"></span></p>
<h3>The Wrong Way: A Single img Tag And JavaScript src Loop</h3>
<p>I previously favored preloading images by applying a single HTML img tag on a page, one without a src attribute and also hidden via CSS:</p>
<pre class="brush: xml; title: ; notranslate">&lt;img id=&quot;hiddenImg&quot; src=&quot;&quot; alt=&quot;&quot; style=&quot;display: none;&quot; /&gt;</pre>
<p>Then, I would create a preloadImages() function, which took as its arguments the paths to the images I wanted to preload. I would then loop through those arguments, setting the src attribute for hiddenImg to be the paths passed to the function:</p>
<pre class="brush: jscript; title: ; notranslate">

function preloadImages() {
	var img = document.getElementById('hiddenImage');
	var i;

	for(i = 0; i &lt; arguments.length; i++) {
		img.src = arguments[i];
	}
}

window.onload = function() {
	preloadImages('i/d01.jpg', 'i/d02.jpg', 'i/d03.jpg', 'i/d04.jpg', 'i/d05.jpg');
}
</pre>
<p>Unfortunately for me, this simply doesn&#8217;t work. And the reason why it doesn&#8217;t work is because, if I pass more than one image to the preloadImages() function, they simply don&#8217;t have enough time to load before the next image is called.</p>
<p>In short, the only image that actually preloads under this methodology is the last one in the arguments list. And that pretty much makes this approach useless.</p>
<p>You can see what I am talking about here: <a href="http://www.dougv.com/demo/js_preload_images/wrong.htm" target="demo">http://www.dougv.com/demo/js_preload_images/wrong.htm</a></p>
<h3>The Dumb Way: Using HTML And CSS</h3>
<p>Better in the technical sense, but just as bad in the practical sense, is using HTML and CSS alone to preload images.</p>
<p>In this case, we simply add, to the end of the page, a bunch of img tags that bring in the pictures we intend to display via JavaScript, based on a DOM event. We either place them inside a hidden div or assign those images to a CSS class that sets them to display: none.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;hiddenImages&quot; style=&quot;display: none;&quot;&gt;
	&lt;img src=&quot;i/a01.jpg&quot; alt=&quot;&quot; /&gt;
	&lt;img src=&quot;i/a02.jpg&quot; alt=&quot;&quot; /&gt;
	&lt;img src=&quot;i/a03.jpg&quot; alt=&quot;&quot; /&gt;
	&lt;img src=&quot;i/a04.jpg&quot; alt=&quot;&quot; /&gt;
	&lt;img src=&quot;i/a05.jpg&quot; alt=&quot;&quot; /&gt;
&lt;/div&gt;
</pre>
<p>You can see an example here: <a href="http://www.dougv.com/demo/js_preload_images/index.htm" target="demo">http://www.dougv.com/demo/js_preload_images/index.htm</a></p>
<p>While this is better than the wrong way, because at least all the images manage to get preloaded, this is dumb. </p>
<p>Suppose our client has disabled JavaScript. This approach doesn&#8217;t care; the images for our JavaScript-driven effects will still load in the background. </p>
<p>In other words, we encumber all the overhead of bringing in effect images for an effect that will not be seen. That&#8217;s wasteful. Maybe it&#8217;s no big deal, given that the average user has plenty of computing power and bandwidth to spare, but it&#8217;s inelegant. And by now, you know that little puts a burr in my butt more than wasteful code.</p>
<h3>Example 1: Using JavaScript&#8217;s appendChild() Method</h3>
<p>The proper way to preload images with JavsScript (and this time, I mean it) is to:</p>
<ul>
<li>create an HTML div that is hidden;</li>
<li>dynamically create an img element for each image we want to preload;</li>
<li>assign each of those dynamically created elements a src attribute that is a path to an image we want to preload; then</li>
<li>append that dynamic img element to the hidden div.</li>
</ul>
<p>So first, the HTML:</p>
<pre class="brush: xml; title: ; notranslate">&lt;div id=&quot;hiddenImages&quot; style=&quot;display: none;&quot;&gt;&lt;/div&gt;</pre>
<p>And next, the JavaScript function:</p>
<pre class="brush: jscript; title: ; notranslate">
function preloadImages() {
	var hiddenDiv = document.getElementById('hiddenImages');
	var i;
	var img;

	for(i = 0; i &lt; arguments.length; i++) {
		img = document.createElement('img');
		img.src = arguments[i];
		img.alt = '';
		hiddenDiv.appendChild(img);
	}
}
</pre>
<p>To invoke this, we simply call the function:</p>
<pre class="brush: jscript; title: ; notranslate">preloadImages('i/b01.jpg', 'i/b02.jpg', 'i/b03.jpg', 'i/b04.jpg', 'i/b05.jpg');</pre>
<p>Witness this in action: <a href="http://www.dougv.com/demo/js_preload_images/example1.htm" target="demo">http://www.dougv.com/demo/js_preload_images/example1.htm</a></p>
<p>I prefer to put the preloadImages() function in the head of the page, and call it just before the closing body tag. </p>
<p>That way, the page gets a chance to load all its elements, before we start calling the images that we intend to show later. In other words, the page gets a chance to at least start loading the images it&#8217;s supposed to be displaying at first glance, before it starts loading the images we&#8217;ll show based on clicks / mouseovers / whatever.</p>
<h3>Example 2: Using jQuery And document.ready</h3>
<p>Of course, no discussion about JavaScript these days is complete without showing a jQuery version. So here&#8217;s mine.</p>
<p>In our case, we can use the same basic methodology as in Example 1. However, there are a few changes:</p>
<ul>
<li>Because jQuery has the .hide() method built-in, we&#8217;ll just hide each image as we create it. That means the div into which we are adding these images need not be hidden at all.</li>
<li>We need to call $(document).ready() sometime after we create the hiddenImages div. Otherwise, jQuery doesn&#8217;t see where it&#8217;s supposed to add the images it&#8217;s creating, and thus silently fails. So, for simplicity&#8217;s sake, I am adding both the preloadImages() function and my call to $(document).ready() just before the closing body tag.</li>
</ul>
<p>So here&#8217;s our hiddenImages div (again, no need to hide it):</p>
<pre class="brush: xml; title: ; notranslate">&lt;div id=&quot;hiddenImages&quot;&gt;&lt;/div&gt;</pre>
<p>And here&#8217;s the JavaScript we place, sometime after it, to preload:</p>
<pre class="brush: jscript; title: ; notranslate">
function preloadImages() {
	for(var i = 0; i &lt; arguments.length; i++) {
		$('&lt;img /&gt;').attr({ src: arguments[i], alt: '' }).appendTo('#hiddenImages').hide();
	}
}

$(document).ready(preloadImages('i/c01.jpg', 'i/c02.jpg', 'i/c03.jpg', 'i/c04.jpg', 'i/c05.jpg'));
</pre>
<p>Working example: <a href="http://www.dougv.com/demo/js_preload_images/example2.htm" target="demo">http://www.dougv.com/demo/js_preload_images/example2.htm</a></p>
<div class="aside">It&#8217;s worth noting that there are a number of image effect examples and plugins at the <a href="http://docs.jquery.com/Tutorials" target="_blank">jQuery tutorial site</a>.</div>
<p>So, whether you prefer to go the old-school JavaScript route, or to get newfangled with jQuery, the proper way to preload an image for DOM-event-based display is to create image elements via JavaScript, then add those elements to some other element on the page &#8212; either an element that&#8217;s already hidden, or by hiding the images as they are created.</p>
<p>You can download the source code here: <a href='http://www.dougv.com/wp-content/uploads/2012/03/js_preload_images.zip'>http://www.dougv.com/wp-content/uploads/2012/03/js_preload_images.zip</a></p>
<p>All links in this post on delicious: <a href="http://delicious.com/dougvdotcom/preloading-images-with-javascript" target="_blank">http://delicious.com/dougvdotcom/preloading-images-with-javascript</a></p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/04/04/displaying-static-random-html-and-images-on-a-web-page-via-ajax/" rel="bookmark">Displaying Static, Random HTML And Images On A Web Page Via AJAX</a> (17)</li>
				<li><a href="https://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/" rel="bookmark">Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM</a> (15.6)</li>
				<li><a href="https://www.dougv.com/2009/06/14/the-simplest-ways-to-do-image-rollover-effects-javascript-and-css-only/" rel="bookmark">The Simplest Ways To Do Image Rollover Effects: JavaScript And CSS-Only</a> (15.4)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/arrays/" title="arrays" rel="tag">arrays</a>, <a href="https://www.dougv.com/tag/coding-standards/" title="coding standards" rel="tag">coding standards</a>, <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a>, <a href="https://www.dougv.com/tag/elegance/" title="elegance" rel="tag">elegance</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2012/03/12/preloading-images-with-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatically Wiring Up XHTML Element Events On Page Load With jQuery</title>
		<link>https://www.dougv.com/2009/06/22/automatically-wiring-up-xhtml-element-events-on-page-load-with-jquery/</link>
		<comments>https://www.dougv.com/2009/06/22/automatically-wiring-up-xhtml-element-events-on-page-load-with-jquery/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 12:30:19 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/?p=2355</guid>
		<description><![CDATA[Many Web developers find themselves in an environment where the design of a Web page is handled by a graphic designer or junior programmer, either as part of their team or from a subcontractor or the client himself. Unfortunately, traditional HTML / XHTML requires most element events handlers &#8212; onmouseover, onclick, onfocus, etc. &#8212; to [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2009/01/09/using-jquery-to-show-a-form-over-a-reduced-opacity-image/" rel="bookmark">Using jQuery To Show A Form Over A Reduced-Opacity Image</a> (17.4)</li>
				<li><a href="https://www.dougv.com/2009/06/13/sorting-your-mysql-results-set-in-php-using-jquery-and-a-more-traditional-approach/" rel="bookmark">Sorting Your MySQL Results Set In PHP Using jQuery (And A More Traditional Approach)</a> (17.3)</li>
				<li><a href="https://www.dougv.com/2009/05/21/parent-child-select-lists-revisited-validating-selected-options-via-jquery-and-php/" rel="bookmark">Parent &#8211; Child Select Lists Revisited: Validating Selected Options Via jQuery And PHP</a> (14.6)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>Many Web developers find themselves in an environment where the design of a Web page is handled by a graphic designer or junior programmer, either as part of their team or from a subcontractor or the client himself.</p>
<p>Unfortunately, traditional HTML / XHTML requires most element events handlers &#8212; onmouseover, onclick, onfocus, etc. &#8212; to be coded as attributes of the tag, like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;img id=&quot;myimage&quot; src=&quot;pic1.jpg&quot; alt=&quot;My Image&quot; onmouseover=&quot;this.src='pic2.jpg'&quot; onmouseout=&quot;this.src='pic1.jpg'&quot; /&gt;
</pre>
<p>That&#8217;s not a problem if you&#8217;re the end point of the code; that is, if the graphic designer hands you a final page that won&#8217;t be modified again. But in the real world, pages and their associated code need to be moved back and forth constantly, with changes aplenty. That can have a real impact on your work, especially if the designer changes or removes your event handlers from page elements.</p>
<p>That&#8217;s the idea behind <a href="http://en.wikipedia.org/wiki/Model-view-controller">MVC (model, view, controller)</a>. We break the chain of custody for a Web request into three parts: A controller accepts a request from the user and determines which model should be used to handle the request.</p>
<p>The selected model, in turn, does something with the request sent to it by the controller; for example, one model might serve up some static content; another model returns search query results; another model returns data based on an environment variable, such as the geolocation of the user&#8217;s IP address (that is, gives a page in Russian to a user from Russia, by default); and so on.</p>
<p>Finally, the view &#8212; the end output the user sees &#8212; is applied by the controller to the model&#8217;s results.</p>
<p>While this is a worthwhile development approach, it may be a bit of overkill for a site that doesn&#8217;t have too much dynamic content, or that simply needs an image rollover effect, a countdown clock, etc. We still want to protect our coding from alteration by the designer, but we don&#8217;t want to employ a $10 solution to a 10-cent problem.</p>
<p>Enter, once again, <a href="http://jquery.com">jQuery</a>, which can automatically bind (that is, &#8220;wire up&#8221;) event handlers for us once the page loads.</p>
<p><span id="more-2355"></span></p>
<h3>$(document).ready() To The Rescue</h3>
<p>The jQuery library includes a class named document (a half-brother of <a href="http://www.w3schools.com/htmldom/dom_obj_document.asp">JavaScript&#8217;s document class</a>) and a method of that class called ready(). This fundamentally acts the same as the <a href="http://www.w3schools.com/jsref/jsref_onload.asp">onload event</a> handler of either the window or body HTML DOM objects in JavaScript &#8212; except that <a href="http://www.learningjquery.com/2006/09/introducing-document-ready">$(document).ready()</a> does not require us to hard-code it into an DOM element.</p>
<p>As always, we start by <a href="http://docs.jquery.com/Downloading_jQuery">downloading the latest version of jQuery</a>, if we haven&#8217;t already done so, and adding a reference to it on our page.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
</pre>
<p>To wire up an event for a single tag, we simply call $(document).ready(), reference the element we want into a <a href="http://docs.jquery.com/Types#Element">jQuery Element object</a>, then <a href="http://docs.jquery.com/Events">bind the event handler</a> we want to use.</p>
<p>You&#8217;ll note in the jQuery documentation that there are several different ways to bind an event to an element. I&#8217;m going to use the most direct method: namely, calling the appropriate event property of the element and assigning a function that way.</p>
<p>Let&#8217;s use the example of an image rollover. Assume we have the following HTML for the image:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;img id=&quot;myimage&quot; src=&quot;out.jpg&quot; alt=&quot;my image&quot; /&gt;
</pre>
<p>Let&#8217;s suppose the rollover image is named over.jpg. Let&#8217;s add &#8212; &#8220;wire up&#8221; &#8212; onmouseover and onmouseout event handlers:</p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function () {
	$(&quot;#myimage&quot;).mouseover(function() {
		$(&quot;#myimage&quot;).attr(&quot;src&quot;, &quot;over.jpg&quot;);
	});
	$(&quot;#myimage&quot;).mouseout(function() {
		$(&quot;#myimage&quot;).attr(&quot;src&quot;, &quot;out.jpg&quot;);
	});
});
</pre>
<p>What if we want to wire up several event handlers? We certainly can do so by coding them individually, as we do above. But we can also wire up the same event handler to all the same elements, elements in the same class, elements with the same attribute, alternating elements, child or sibling elements, etc. &#8212; pretty much any relationship or similarity can be accounted for.</p>
<p>Suppose we want to pop up an alert box, any time a checkbox is checked, with the value of that checkbox:</p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function () {
	$(&quot;input[type='checkbox']&quot;).click(function() {
		alert(&quot;You just clicked the &quot; + $(this).val() + &quot; checkbox!&quot;);
	});
});
</pre>
<p>Or maybe, we want to change the background color of all alternate table rows; change the color of a row when we mouse over it; and change the color of a row when we click on it:</p>
<pre class="brush: jscript; title: ; notranslate">
$(document).ready(function () {
	$(&quot;tr:even&quot;).addClass(&quot;row-alt&quot;);
	$(&quot;td&quot;).mouseover(function() {
		$(this).parent().addClass(&quot;row-over&quot;);
	});
	$(&quot;td&quot;).mouseout(function() {
		$(this).parent().removeClass(&quot;row-over&quot;);
	});
	$(&quot;td&quot;).click(function() {
		$(this).parent().toggleClass(&quot;row-click&quot;);
	});
});
</pre>
<pre class="brush: css; title: ; notranslate">
.row-alt {
	background-color: #eee;
}

.row-over {
	background-color: #ffc;
}

.row-click {
	background-color: #fc9;
}
</pre>
<p>You can see all of these in effect here: <a href="http://www.dougv.com/demo/jquery_event_wireup/">http://www.dougv.com/demo/jquery_event_wireup/</a></p>
<p>I distribute code under the GNU GPL version 3.</p>
<p>Hopefully, this gives you an idea of the power of jQuery, and its ability to help you adopt <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented concepts</a>, such as modularity and abstraction, in your traditional Web projects.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2009/01/09/using-jquery-to-show-a-form-over-a-reduced-opacity-image/" rel="bookmark">Using jQuery To Show A Form Over A Reduced-Opacity Image</a> (17.4)</li>
				<li><a href="https://www.dougv.com/2009/06/13/sorting-your-mysql-results-set-in-php-using-jquery-and-a-more-traditional-approach/" rel="bookmark">Sorting Your MySQL Results Set In PHP Using jQuery (And A More Traditional Approach)</a> (17.3)</li>
				<li><a href="https://www.dougv.com/2009/05/21/parent-child-select-lists-revisited-validating-selected-options-via-jquery-and-php/" rel="bookmark">Parent &#8211; Child Select Lists Revisited: Validating Selected Options Via jQuery And PHP</a> (14.6)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2009/06/22/automatically-wiring-up-xhtml-element-events-on-page-load-with-jquery/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>JavaScript Function Arguments: They&#8217;re An Array And You Can Treat Them As Such</title>
		<link>https://www.dougv.com/2009/06/20/javascript-function-arguments-theyre-an-array-and-you-can-treat-them-as-such/</link>
		<comments>https://www.dougv.com/2009/06/20/javascript-function-arguments-theyre-an-array-and-you-can-treat-them-as-such/#comments</comments>
		<pubDate>Sat, 20 Jun 2009 16:22:46 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>
		<category><![CDATA[elegance]]></category>
		<category><![CDATA[objects and classes]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/?p=2342</guid>
		<description><![CDATA[One of the nicest features of JavaScript is the ability to treat function arguments as an array. We all know how to write a function that takes a known number of arguments: But sometimes, your script will require you to pass some unknown number of parameters to a function. So how do you deal with [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/07/03/working-with-a-simple-structure-array-in-vbnet/" rel="bookmark">Working With A Simple Structure Array In VB.NET</a> (17.7)</li>
				<li><a href="https://www.dougv.com/2007/07/04/in-reply-to-comments-made-on-working-with-a-simple-structure-array-in-vbnet/" rel="bookmark">In Reply To Comments Made On &quot;Working With A Simple Structure Array In VB.NET&quot;</a> (16.2)</li>
				<li><a href="https://www.dougv.com/2007/01/15/dynamically-populating-a-listbox-from-a-textbox-via-javascript-dom/" rel="bookmark">Dynamically Populating A Listbox From A Textbox Via JavaScript / DOM</a> (14.5)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>One of the nicest features of JavaScript is the ability to treat function arguments as an array. We all know how to write a function that takes a known number of arguments:</p>
<pre class="brush: jscript; title: ; notranslate">
function foo(bar) {
	alert(bar);
}

function getArea(shape, measure, unit) {
	var output = 'The area of a ' + measure + ' ' + unit + ' ' + shape + ' is ';
	switch(shape) {
		case 'square':
			output += (measure * measure);
			break;
		case 'circle':
			output += (3.14 * (measure * measure));
			break;
		default:
			output += 'unknown to this function.';
	}
	alert(output);
}
</pre>
<p>But sometimes, your script will require you to pass some unknown number of parameters to a function. So how do you deal with that?</p>
<p>Luckily, JavaScript functions treat all of their arguments as an array. So, if you&#8217;re not certain how many arguments your function will take, don&#8217;t declare them in your function code; simply use the reserved word arguments to iterate the array of arguments passed to the function.</p>
<p><span id="more-2342"></span></p>
<pre class="brush: jscript; title: ; notranslate">
function allTheAnimals() {
	var output = 'The animals you provided are: ';
	for(var i = 0; i &lt; arguments.length; i++) {
		output += arguments[i] + ', ';
	}
	output = output.substring(0, (output.length - 2)); //remove trailing comma and space
	alert(output);
}
</pre>
<p>Note that we can ask for specific indexes of the array, but should ensure there are at least that many elements in the array before asking:</p>
<pre class="brush: jscript; title: ; notranslate">
function threeIsAMagicNumber() {
	if(arguments.length &lt; 3) {
		alert('There is no third argument!');
	}
	else {
		alert('The value of the third argument passed to this function is ' + arguments[2].toString());
	}
}
</pre>
<p>We can even pass an unknown number of arguments from one function to another, via the <a href="http://www.webreference.com/js/column26/apply.html">apply method</a>:</p>
<pre class="brush: jscript; title: ; notranslate">
function parentFunction() {
	var output = 'Arguments received by parent function: ';
	for(var i = 0; i &lt; arguments.length; i++) {
		output += arguments[i] + ', ';
	}
	output = output.substring(0, (output.length - 2));
	output += &quot;\n\nDo you want to send these to the child function? OK to submit to child function, Cancel to abort.&quot;;
	if(confirm(output)) {
		childFunction.apply(this, arguments);
	}
}

function childFunction() {
	var output = 'Arguments received by the child function: ';
	for(var i = 0; i &lt; arguments.length; i++) {
		output += arguments[i] + ', ';
	}
	output = output.substring(0, (output.length - 2));
	alert(output);
}
</pre>
<p>You can see a demonstration of all these here: <a href="http://www.dougv.com/demo/js_function_arguments_array/">http://www.dougv.com/demo/js_function_arguments_array/</a></p>
<p>I distribute code under the GNU GPL version 3.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/07/03/working-with-a-simple-structure-array-in-vbnet/" rel="bookmark">Working With A Simple Structure Array In VB.NET</a> (17.7)</li>
				<li><a href="https://www.dougv.com/2007/07/04/in-reply-to-comments-made-on-working-with-a-simple-structure-array-in-vbnet/" rel="bookmark">In Reply To Comments Made On &quot;Working With A Simple Structure Array In VB.NET&quot;</a> (16.2)</li>
				<li><a href="https://www.dougv.com/2007/01/15/dynamically-populating-a-listbox-from-a-textbox-via-javascript-dom/" rel="bookmark">Dynamically Populating A Listbox From A Textbox Via JavaScript / DOM</a> (14.5)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a>, <a href="https://www.dougv.com/tag/elegance/" title="elegance" rel="tag">elegance</a>, <a href="https://www.dougv.com/tag/objects-and-classes/" title="objects and classes" rel="tag">objects and classes</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2009/06/20/javascript-function-arguments-theyre-an-array-and-you-can-treat-them-as-such/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Simplest Ways To Do Image Rollover Effects: JavaScript And CSS-Only</title>
		<link>https://www.dougv.com/2009/06/14/the-simplest-ways-to-do-image-rollover-effects-javascript-and-css-only/</link>
		<comments>https://www.dougv.com/2009/06/14/the-simplest-ways-to-do-image-rollover-effects-javascript-and-css-only/#comments</comments>
		<pubDate>Sun, 14 Jun 2009 16:17:18 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>
		<category><![CDATA[elegance]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/?p=2231</guid>
		<description><![CDATA[A common question on Yahoo! Answers is how to do image rollover effects simply. There are two ways to do so: With JavaScript, and via CSS alone. Of the two, I prefer the JavaScript method, as it doesn&#8217;t require marking up your code too much; but the CSS method is fine, too, and takes away [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/10/03/simple-image-rollover-via-css-only/" rel="bookmark">Simple Image Rollover Via CSS Only</a> (48.3)</li>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (26.2)</li>
				<li><a href="https://www.dougv.com/2006/12/14/changing-css-styles-via-javascript-based-on-the-users-web-browser/" rel="bookmark">Changing CSS Styles Via JavaScript, Based On The User&#039;s Web Browser</a> (23.4)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>A common question on Yahoo! Answers is how to do image rollover effects simply.</p>
<p>There are two ways to do so: With JavaScript, and via CSS alone. Of the two, I prefer the JavaScript method, as it doesn&#8217;t require marking up your code too much; but the CSS method is fine, too, and takes away the worry of dealing with users who have disabled JavaScript in their browsers.</p>
<p>This topic also allows me to address the best way to &#8220;preload&#8221; images for use via JavaScript / CSS; previous articles I&#8217;ve written have used less efficient methods, and I&#8217;d like to go on record with the proper way to preload.</p>
<p>Last things first, then. The proper way to &#8220;preload&#8221; images is to use a standard XHTML img tag, using a CSS class to &#8220;hide&#8221; the image(s) being preloaded via display: none. These images should then appear directly before the closing body tag, to speed page loading by loading the &#8220;preloaded&#8221; images last.</p>
<pre class="brush: css; title: ; notranslate">
img.hide {
        display: none;
}
</pre>
<pre class="brush: xml; title: ; notranslate">
        &lt;img src=&quot;home-over.png&quot; alt=&quot;&quot; class=&quot;hide&quot; /&gt;
        &lt;img src=&quot;about-over.png&quot; alt=&quot;&quot; class=&quot;hide&quot; /&gt;
        &lt;img src=&quot;services-over.png&quot; alt=&quot;&quot; class=&quot;hide&quot; /&gt;
        &lt;img src=&quot;contact-over.png&quot; alt=&quot;&quot; class=&quot;hide&quot; /&gt;
&lt;/body&gt;
</pre>
<p>Using CSS to hide images should work for all current Web browsers, including versions 5+ of Internet Explorer.</p>
<p><span id="more-2231"></span></p>
<h3>CSS-Only Rollovers</h3>
<p>You can create CSS-only rollovers. However, there are two drawbacks to this approach.</p>
<p>Because this method uses CSS, appearance problems may arise with various browsers, especially versions of Internet Explorer prior to version 8, but any browser that&#8217;s more than a couple years old could render things oddly.</p>
<p>The CSS only route basically replaces all rollover-effect img tags with div tags. Each such div receives a unique ID, so we can write CSS that targets just that item. Because of that, you cannot add alt attributes to your images; and this will affect their ability to index with image search engines. (Some people may see that as a benefit; but for those who want their images to index well, this method will likely seriously impede that desire.)</p>
<p>We first set the CSS properties of all the rollover div elements, fixing their display as inline-table. We do that because we want to ensure the image will flow into our layout; most Web browsers treat div elements as block elements, meaning that they appear as though they are followed by a br. That, generally speaking, will prevent our div-nee-img from lining up properly in most layouts.</p>
<pre class="brush: css; title: ; notranslate">
#home, #about, #services, #contact, #leelee {
	display: inline-table;
}
</pre>
<p>Next, we fix the size of each div to be the same as the background image we will use, and make that background image the normal, or &#8220;up,&#8221; state of the image:</p>
<pre class="brush: css; title: ; notranslate">
#home {
	width: 45px;
	height: 20px;
	background: #ddd url(images/home.png) no-repeat;
}

#about {
	width: 45px;
	height: 20px;
	background: #ddd url(images/about.png) no-repeat;
}

#services {
	width: 65px;
	height: 20px;
	background: #ddd url(images/services.png) no-repeat;
}

#contact {
	width: 60px;
	height: 20px;
	background: #ddd url(images/contact.png) no-repeat;
}

#leelee {
	float: left;
	padding-right: 10px;
	width: 154px;
	height: 300px;
	background: #fff url(images/leelee1.jpg) no-repeat;
}
</pre>
<p>To actually do the rollovers, we create a :hover pseudoclass effect, which changes the background of the given div to be the image we want shown on mouseover.</p>
<p>Note that not only can we change the height and width of the image, we can add or remove any effect we&#8217;d like, as well, such as changing the border color.</p>
<pre class="brush: css; title: ; notranslate">
#home:hover {
	background: #ddd url(images/home-over.png) no-repeat;
}

#about:hover {
	background: #ddd url(images/about-over.png) no-repeat;
}

#services:hover {
	background: #ddd url(images/services-over.png) no-repeat;
}

#contact:hover {
	background: #ddd url(images/contact-over.png) no-repeat;
}

#leelee:hover {
	width: 200px;
	height: 300px;
	background: #fff url(images/leelee2.jpg) no-repeat;
}
</pre>
<p>And with that, we have CSS-only rollovers. You can see this in action here: <a href="http://www.dougv.com/demo/js_image_rollovers/index.html">http://www.dougv.com/demo/js_image_rollovers/index.html</a></p>
<h3>JavaScript Rollovers</h3>
<p>The benefit of the JavaScript approach is that it uses actual images to achieve its rollover effects. However, this methodology requires you to add onmouseover and onmouseout event handlers to your rollover images&#8217; tags; while that doesn&#8217;t mean more coding versus the CSS-only methodology, it does mean tinkering with XHTML source code, which some users might be reluctant to do for design / team development / WYSIWYG editor issues that may raise.</p>
<p>A way to avoid adding event handlers directly to your image tags is to <a href="http://www.dougv.com/2009/06/22/automatically-wiring-up-xhtml-element-events-on-page-load-with-jquery/">use a library, such as jQuery, that allows you to add event handlers</a> via JavaScript.</p>
<p>Under the JavaScript method, we again preload our images. And we then use img tags to place our &#8220;up-state&#8221; images wherever we want them to go.</p>
<p>We then add onmouseover and onmouseout event handlers to each tag. Using the reserved word this, which tells JavaScript we mean the image that is triggering the event, we change the image&#8217;s src attribute to be the path to whichever image we want to have displayed.</p>
<p>In the case of onmouseover, we want the &#8220;down-state&#8221; image to replace the &#8220;up-state&#8221; image; with onmouseout, we want the &#8220;up-state&#8221; image restored.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;img src=&quot;images/home.png&quot; alt=&quot;Home&quot; onmouseover=&quot;this.src='images/home-over.png'&quot; onmouseout=&quot;this.src='images/home.png'&quot; /&gt;
&lt;img src=&quot;images/about.png&quot; alt=&quot;About&quot; onmouseover=&quot;this.src='images/about-over.png'&quot; onmouseout=&quot;this.src='images/about.png'&quot; /&gt;
&lt;img src=&quot;images/services.png&quot; alt=&quot;Services&quot; onmouseover=&quot;this.src='images/services-over.png'&quot; onmouseout=&quot;this.src='images/services.png'&quot; /&gt;
&lt;img src=&quot;images/contact.png&quot; alt=&quot;Contact&quot; onmouseover=&quot;this.src='images/contact-over.png'&quot; onmouseout=&quot;this.src='images/contact.png'&quot; /&gt;

&lt;img id=&quot;leelee&quot; src=&quot;images/leelee1.jpg&quot; alt=&quot;Leelee Sobieski&quot; onmouseover=&quot;this.src='images/leelee2.jpg'&quot; onmouseout=&quot;this.src='images/leelee1.jpg'&quot; /&gt;
</pre>
<p>And that&#8217;s all there is to that. You can see a working demo here: <a href="http://www.dougv.com/demo/js_image_rollovers/js.html">http://www.dougv.com/demo/js_image_rollovers/js.html</a></p>
<p>I distribute all code under the GNU GPL version 3.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/10/03/simple-image-rollover-via-css-only/" rel="bookmark">Simple Image Rollover Via CSS Only</a> (48.3)</li>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (26.2)</li>
				<li><a href="https://www.dougv.com/2006/12/14/changing-css-styles-via-javascript-based-on-the-users-web-browser/" rel="bookmark">Changing CSS Styles Via JavaScript, Based On The User&#039;s Web Browser</a> (23.4)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a>, <a href="https://www.dougv.com/tag/elegance/" title="elegance" rel="tag">elegance</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2009/06/14/the-simplest-ways-to-do-image-rollover-effects-javascript-and-css-only/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using jQuery To Show A Form Over A Reduced-Opacity Image</title>
		<link>https://www.dougv.com/2009/01/09/using-jquery-to-show-a-form-over-a-reduced-opacity-image/</link>
		<comments>https://www.dougv.com/2009/01/09/using-jquery-to-show-a-form-over-a-reduced-opacity-image/#comments</comments>
		<pubDate>Fri, 09 Jan 2009 05:43:57 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/?p=1402</guid>
		<description><![CDATA[It&#8217;s an awful thing, waiting for a question at Yahoo! Answers that would be fun to discuss as a blog entry. There is an awful lot of chaff to be sorted before one finds such wheat, and even then, sometimes the supposed grains turn out to be mouse turds. Consider the following: How would this [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (18.5)</li>
				<li><a href="https://www.dougv.com/2006/12/19/showing-or-hiding-html-form-elements-with-javascript/" rel="bookmark">Showing Or Hiding HTML Form Elements With JavaScript</a> (14.8)</li>
				<li><a href="https://www.dougv.com/2007/10/03/simple-image-rollover-via-css-only/" rel="bookmark">Simple Image Rollover Via CSS Only</a> (14.8)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s an awful thing, waiting for a question at Yahoo! Answers that would be fun to discuss as a blog entry. There is an awful lot of chaff to be sorted before one finds such wheat, and even then, sometimes the supposed grains turn out to be mouse turds.</p>
<p>Consider the following:</p>
<blockquote><p><strong><a href="http://answers.yahoo.com/question/index?qid=20090108191323AAzvIJV">How would this be done? Java, flash, php, etc?</a></strong><br />
Okay, for my site.. on the main page, i have four main pictures lined next to eachother..</p>
<p>each one is linked.</p>
<p>The site can be logged into, logged out, you can create an account on it, etc.</p>
<p>What i want to do though, is when a member clicks on one of the pictures, per se if one picture was a large rectangle and it was linked to the login deal,<br />
i would want the picture to fade out, as then the login deal would appear within the rectangle of the picture.</p>
<p>for example:</p>
<p>|&#8220;&#8220;&#8220;&#8220;&#8220;&#8220;&#8220;`|<br />
|&#8220;&#8220;`pic&#8220;&#8220;&#8220;|<br />
|&#8220;&#8220;&#8220;&#8220;&#8220;&#8220;&#8220;`|<br />
&#8212;&#8212;&#8212;&#8212;&#8212;-</p>
<p>user clicks on pic:</p>
<p>_________ &#8220;&#8220;&#8220;&#8220;&#8220;&#8220;`_________<br />
|&#8212;&#8212;&#8212;&#8212;&#8212;|&#8220;&#8220;&#8220;&#8220;&#8220;&#8220;`|-user[     ]-|<br />
|-fade out&#8211;|&#8220;&#8220;&#8212;&gt;&#8220;&#8220;|-pass[    ]&#8211;|<br />
|&#8212;&#8212;&#8212;&#8212;&#8212;|&#8220;&#8220;&#8220;&#8220;&#8220;&#8220;`|-submit&#8230;<br />
&#8212;&#8212;&#8212;&#8212;&#8212;-&#8220;&#8220;&#8220;&#8220;&#8220;&#8220;`&#8212;&#8212;&#8212;&#8230;</p>
<p>how would i do this?</p>
<p>i&#8217;m thinkin Java.. but does anyone know of any tutorials on how to do this or anything?</p>
<p>thanks</p>
<p>hope the diagram makes sense. ha</p></blockquote>
<p>Hoo, boy. A compelling problem, wrapped in a complete abortion of a question. What should I do?</p>
<p><span id="more-1402"></span></p>
<p>I want to solve this, especially since it gives me my first chance to discuss <a href="http://jquery.com/">jQuery</a>, with which I have fallen completely in love. But I don&#8217;t want to reward the total disregard for common sense, the English language and basic programming terminology exhibited in this question, either.</p>
<ul>
<li>&#8220;Per se&#8221; is Latin for &#8220;by itself.&#8221; It is most commonly used by lawyers as a synonym for &#8220;inherently,&#8221; as in, &#8220;A slippery floor is hazardous <em>per se</em>, but a sign that warns the floor is wet helps mitigate the floor owner&#8217;s liability.&#8221; &#8220;Per se&#8221; is not used to introduce an example. &#8220;Say&#8221; is used for that purpose. It might seem like picking nits, but it is absolutely impossible to take people seriously if they so blatantly misuse words.</li>
<li>&#8220;Java&#8221; is not shorthand for &#8220;JavaScript&#8221; (a fact the questioner later realized). Java and JavaScript are completely different things, the way <a href="http://gawker.com/news/drugs/whitney-houstons-bathroom-messy-crack-mecca-163721.php">crack cocaine</a> and <a href="http://www.crackerjack.com/">Cracker Jack</a> are completely different things. It is impossible to take a Web designer seriously if he doesn&#8217;t understand that Java and JavaScript aren&#8217;t the same thing, or at best, that he cannot use the terms interchangeably, the same way no one asks for an eight ball of candy-coated popcorn and peanuts.</li>
<li>At least, the questioner figured out that the ASCII drawing ought to be replaced by an actual drawing. The amusing thing is, neither was needed; his text description was fine.</li>
</ul>
<p>OK, my spleen is vented. Let&#8217;s do this thing.</p>
<h4>The Basic Approach: jQuery Does The Dirty Work</h4>
<p>With all this question&#8217;s failings, its aim is clear:</p>
<ul>
<li>There&#8217;s a full-opacity image.</li>
<li>User clicks on that image.</li>
<li>Image fades down to limited opacity.</li>
<li>Form fades up to full opacity over image.</li>
</ul>
<p>This is easy as pie to do, and thanks to jQuery, we don&#8217;t even need to code much. The nice thing about jQuery is that it works as a cross-browser implementation of certain DOM manipulation effects; among those stock effects is fading elements up and down. So we&#8217;ll use this version of the wheel to achieve our desired effect.</p>
<p>So our first task is to <a href="http://docs.jquery.com/Downloading_jQuery">download jQuery&#8217;s current release</a>.</p>
<p><em>A quick aside on minimized / packed / uncompressed script:</em> It doesn&#8217;t really matter which jQuery source file you download (minimized / packed / uncompressed). You only need to download one, and which one is up to you.</p>
<p>The only difference between the three is how long it takes each to download to the client browser, and in this cheap, high-bandwidth world, the difference in download times between a 31 kb (packed) file and a 94 kb (uncompressed) file is nothing. Heck, it&#8217;s nothing in the dial-up world. But since it doesn&#8217;t matter, use the packed version; elegance alone suggests that&#8217;s best.</p>
<p>To use the library, we simply post it on our site and make it the source of a script tag in the header of our Web page.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot; src=&quot;jquery-1.2.6.pack.js&quot;&gt;&lt;/script&gt;
</pre>
<p>Now, for the work we need to put into this: Some images, some HTML and a tiny bit of JavaScript to invoke jQuery methods that otherwise would have taken hours to write.</p>
<h4>The HTML and CSS</h4>
<p>We&#8217;re going to display our four-across layout as div elements. More specifically, we&#8217;ll fix the size of four divs, then lay them side by side. And each will contain the image we want to show.</p>
<p>We&#8217;ve got a trick up our sleeve, however. Each of these divs is also going to have a background image version &#8212; which is a 30% opacity version of the original.</p>
<p>For example, if div no. 1 initially contains an image named 1.jpg, then it also has a background image named 1.30.jpg. This background image is the 30% opacity version of 1.jpg.</p>
<p>We do this because we want a faded version of the image to be the background for our form. So, we go ahead and make that faded image the background.</p>
<p>When the 100% opacity image is showing, it hides the background version; as it fades out, the background image appears, and as the opacity of the original image gets less than the 30 percent of the background image, the naked eye doesn&#8217;t notice this; it appears that the fading stopped at 30 percent. When we fade the image back up, it will appear to the naked eye that the 30% opacity image has faded up.</p>
<p>Let&#8217;s start with the CSS we&#8217;ll apply to our page:</p>
<ul>
<li>Create a containing div; fixed at 1250px, with auto left and right margins.</li>
<li>Create a common class, called panel, which sets the width and height of each div to be that of the images to be used, floats them all left and gives them all a right margin of 10 px, among other styles;</li>
<li>Specify the background images for each of these divs;</li>
<li>Apply a padding to the login form, and initially set its display to none, so that the image is shown instead of the form.</li>
</ul>
<pre class="brush: css; title: ; notranslate">
div#container {
	width: 1250px;
	margin: 10px auto;
}

div.panel {
	width: 300px;
	height: 195px;
	float: left;
	margin-right: 10px;
	border: 1px solid #000;
	cursor: pointer;
}

div#panel1 {
	background-image: url(1.30.jpg);
}

div#panel2 {
	background-image: url(2.jpg);
}

div#panel3 {
	background-image: url(3.jpg);
}

div#panel4 {
	background-image: url(4.jpg);
}

#loginform {
	padding: 5px;
	display: none;
}
</pre>
<p>With the CSS out of the way, we can build the basic HTML of the page. I&#8217;m being lazy here; I&#8217;m only going to make one of these divs interactive. The principles I am applying to the first div will work on all four.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div id=&quot;container&quot;&gt;
    &lt;div id=&quot;panel1&quot; class=&quot;panel&quot;&gt;
        &lt;img id=&quot;img1&quot; src=&quot;1.jpg&quot; alt=&quot;Click Here To Log In&quot; title=&quot;Click Here To Log In&quot; onclick=&quot;toggleLoginForm()&quot; /&gt;
        &lt;form id=&quot;loginform&quot; action=&quot;&quot; method=&quot;post&quot;&gt;
            &lt;label&gt;User ID: &lt;input type=&quot;text&quot; id=&quot;tbUser&quot; name=&quot;tbUser&quot;/&gt;&lt;/label&gt;
            &lt;br /&gt;
            &lt;label&gt;Password: &lt;input type=&quot;password&quot; id=&quot;tbPass&quot; name=&quot;tbPass&quot; /&gt;&lt;/label&gt;
            &lt;br /&gt;
            &lt;input type=&quot;submit&quot; id=&quot;btnSubmit&quot; name=&quot;btnSubmit&quot; value=&quot;Log In&quot; onclick=&quot;toggleLoginForm()&quot; /&gt;
        &lt;/form&gt;
    &lt;/div&gt;
    &lt;div id=&quot;panel2&quot; class=&quot;panel&quot;&gt;&lt;/div&gt;
    &lt;div id=&quot;panel3&quot; class=&quot;panel&quot;&gt;&lt;/div&gt;
    &lt;div id=&quot;panel4&quot; class=&quot;panel&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>Note that both img#img1 and input#btnSubmit have the as-yet-undefined JavaScript function toggleLoginForm() assigned to their onclick events. Let&#8217;s get to describing that function.</p>
<h4>The JavaScript</h4>
<p>Thanks to jQuery, fading DOM elements in and out is as simple as calling the methods fadeIn and fadeOut.</p>
<p>In jQuery, you can address elements in a number of ways. When you want to address an element by its ID attribute, you do that the same way you do in CSS: apply a hash mark, followed by the ID value. For example, if I want to address the div with ID of panel1: $(&#8216;#panel1&#8242;) gets me a reference to that element.</p>
<p>The <a href="http://docs.jquery.com/Effects/fadeIn">fadeIn</a> and <a href="http://docs.jquery.com/Effects/fadeOut">fadeOut</a> effects in jQuery take two arguments: speed and, optionally, a callback function.</p>
<p>A <em>callback function</em> is a function that a function will call after it is done. This is of great use to us, because it makes the fading effect much smoother. For example, we could do this:</p>
<pre class="brush: jscript; title: ; notranslate">
$('#img1').fadeOut(&quot;slow&quot;);
$('#loginform').fadeIn(&quot;slow&quot;);
</pre>
<p>But if we do that, the fading out of the image and the fading in of the form take place nearly simultaneously, and this creates a very rough transition in the middle of the effect, where both elements are about half visible.</p>
<p>For a smoother transition, we completely fade out the currently visible element &#8212; either the image or the form &#8212; then &#8220;call back&#8221; the fade in effect on the invisible element. We determine which element fades in or out by asking JavaScript if the form is currently visible (more accurately, if its CSS display property is set to none). When the form is not showing, we need to fade the image out and fade the form in; vice-versa when the form is visible.</p>
<pre class="brush: jscript; title: ; notranslate">
function toggleLoginForm() {
	if($('#loginform').css('display') == &quot;none&quot;) {
		$('#img1').fadeOut(&quot;slow&quot;, function() { $('#loginform').fadeIn(&quot;slow&quot;); });
	}
	else {
		$('#loginform').fadeOut(&quot;slow&quot;, function() { $('#img1').fadeIn(&quot;slow&quot;); });
	}
}
</pre>
<p>You can see the script in action here:</p>
<p><a href="http://www.dougv.com/demo/jquery_fade/">http://www.dougv.com/demo/jquery_fade/</a></p>
<p>Just click on the image of the lady holding the cat to see the effect; download the page to your computer to get all the code. I distribute all code under the GNU GPL version 3.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (18.5)</li>
				<li><a href="https://www.dougv.com/2006/12/19/showing-or-hiding-html-form-elements-with-javascript/" rel="bookmark">Showing Or Hiding HTML Form Elements With JavaScript</a> (14.8)</li>
				<li><a href="https://www.dougv.com/2007/10/03/simple-image-rollover-via-css-only/" rel="bookmark">Simple Image Rollover Via CSS Only</a> (14.8)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2009/01/09/using-jquery-to-show-a-form-over-a-reduced-opacity-image/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Showing A Larger Image From A Thumbnail OnClick Via JavaScript / DOM Revisited</title>
		<link>https://www.dougv.com/2008/01/28/showing-a-larger-image-from-a-thumbnail-onclick-via-javascript-dom-revisited/</link>
		<comments>https://www.dougv.com/2008/01/28/showing-a-larger-image-from-a-thumbnail-onclick-via-javascript-dom-revisited/#comments</comments>
		<pubDate>Tue, 29 Jan 2008 04:15:21 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/2008/01/28/showing-a-larger-image-from-a-thumbnail-onclick-via-javascript-dom-revisited/</guid>
		<description><![CDATA[Recently asked on Yahoo! Answers: Showing a Larger picture from a Thumbnail &#8211; How to include the Title? I have followed the steps from http://www.dougv.com/2007/02/07/sho&#8230; using the iFrame version, but cannot get the image on click to display the title used in the img tag. i.e Using the Addendum: information posted the title that gets [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/02/07/showing-a-larger-image-from-a-thumbnail-onclick-via-javascript-dom/" rel="bookmark">Showing A Larger Image From A Thumbnail OnClick Via JavaScript / DOM</a> (88.5)</li>
				<li><a href="https://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/" rel="bookmark">Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM</a> (71.8)</li>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (34.6)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>Recently asked on Yahoo! Answers:</p>
<blockquote><p><strong><a href="http://au.answers.yahoo.com/question/index?qid=20080128162347AA0zdpH">Showing a Larger picture from a Thumbnail &#8211; How to include the Title?</a></strong><br />
I have followed the steps from <a href="http://www.dougv.com/2007/02/07/showing-a-larger-image-from-a-thumbnail-onclick-via-javascript-dom/">http://www.dougv.com/2007/02/07/sho&#8230;</a><br />
using the iFrame version, but cannot get the image on click to display the title used in the img tag.</p>
<p>i.e
<pre class="brush: xml; title: ; notranslate">&lt;img src=&quot;images/image_02_tn.jpg&quot; alt=&quot;image_02.jpg&quot; title=&quot;image name&quot; /&gt;</pre>
<p>Using the Addendum: information posted the title that gets displayed is &#8216;image_02.jpg&#8217; when I want &#8216;Image Name&#8217; to be displayed.</p>
<p>Anyone know the best way to do this?</p></blockquote>
<p>A few changes to the original script take care of this request quite handily, and it also allows me the opportunity to make some improvements to the original script:</p>
<ul>
<li>Modern Web browsers support the onclick event for any DOM element, so there&#8217;s no need to assign the onclick event to a hyperlink; we can add it directly to the thumbnails.</li>
<li>We should preload the full-size images so that there isn&#8217;t a significant delay between when the thumbnails have been clicked and the full-size image shows.</li>
<li>To allow the script to pull images from any location, I&#8217;ve removed the part of the script that sets a path and concatenates the relevant image to that path.</li>
</ul>
<p>Let&#8217;s get to it. As always, I will have a working demo and code you can download at the end of this entry.</p>
<p><span id="more-316"></span></p>
<h4>Step 1: The preLoadImages() Function</h4>
<p>A image preloader is easy to accomplish. We simply create a JavaScript function that makes, for each image passed to the function, a new Image() object, and assigns to that object&#8217;s src attribute the URL of the image we want preloaded.</p>
<pre class="brush: jscript; title: ; notranslate">
function preLoadImages() {
	var tmp = new Array();
	for(var i = 0; i &lt; attributes.length; i++) {
		tmp[i] = new Image();
		tmp[i].src = attributes[i];
	}
}
</pre>
<p>We also alter the BODY tag in our page&#8217;s HTML to call the function, with each full-sized image listed as an argument:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;body onload=&quot;preLoadImages('images/jessica_biel_01.jpg', 'images/jessica_biel_02.jpg', 'images/jessica_biel_03.jpg', 'images/jessica_biel_04.jpg', 'images/jessica_biel_05.jpg', 'images/jessica_biel_06.jpg', 'images/jessica_biel_07.jpg', 'images/jessica_biel_08.jpg');&quot;&gt;
</pre>
<p>If you use the IFRAME version of this script, this function can go on either the page that shows the full-sized image or the thumbnail page; I prefer using the full-size image page, just to keep things associated properly (the images appear on that page, so that page should preload the images).</p>
<h4>Step 2: Changes To The HTML</h4>
<p>For our new text area to work, we need to make some changes to the HTML on the page.</p>
<p>As I noted above, we can get rid of the hyperlinks surrounding the thumbnails. We&#8217;re also going to change the showImage() function to accept two arguments, rather than one: The first argument will be the path to the image we want to show, and the second argument will be the text we want to have displayed under the image.</p>
<p>Finally, we need to add a DIV where we will display the text associated with the image.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;img src=&quot;images/jessica_biel_09_tn.jpg&quot; alt=&quot;images/jessica_biel_09_tn.jpg&quot; title=&quot;images/jessica_biel_09_tn.jpg&quot; onclick=&quot;showImage('images/jessica_biel_09.jpg', 'And even if she sits in the bathroom sink for no apparent reason.');&quot; /&gt;

&lt;div id=&quot;rightText&quot;&gt;
	This is where the text associated with each image will appear.
&lt;/div&gt;
</pre>
<h4>Step 3: Changes To The showImage() Function</h4>
<p>As noted above, the showImage() JavaScript function now takes two arguments: the full path to the image we want to display full-sized when the thumbnail is clicked, and the text we want to have appear alongside that image.</p>
<p>Our function now works as follows:</p>
<ol>
<li>We get a reference to the full-sized image using getElementById()</li>
<li>We reference the new text display DIV, also via getElementById()</li>
<li>We establish the source, alt and title attributes of the full-sized image to be the path provided by the first argument of the function.</li>
<li>We set the innerHTML of the text display DIV to be the text passed as the second argument of the function.</li>
</ol>
<pre class="brush: jscript; title: ; notranslate">
function showImage(imgName, imgText) {
	var curImage = document.getElementById('currentImg');
	var textDiv = document.getElementById('rightText');

	curImage.src = imgName;
	curImage.alt = imgName;
	curImage.title = imgName;
	textDiv.innerHTML = imgText;
}
</pre>
<p>Some usage notes:</p>
<ul>
<li>Any HTML you pass as the second argument of the function will display as HTML in the text DIV. For example, if you use a STRONG tag in the DIV, whatever is inside the STRONG tags will be bold.</li>
<li>You need to escape all single-quotes in your HTML function calls and replace all double-quotes with the HTML entity for double-quotes. In fact, it makes a lot of sense to replace all special characters with their HTML entities.</li>
</ul>
<pre class="brush: xml; title: ; notranslate">
&lt;!-- escape or replace your quotes! --&gt;
&lt;img src=&quot;images/jessica_biel_02_tn.jpg&quot; alt=&quot;images/jessica_biel_02_tn.jpg&quot; title=&quot;images/jessica_biel_02_tn.jpg&quot; onclick=&quot;showImage('images/jessica_biel_02.jpg', 'If you use quotes in your text, it's important to escape them with a backslash.');&quot; /&gt;
&lt;br /&gt;
&lt;img src=&quot;images/jessica_biel_03_tn.jpg&quot; alt=&quot;images/jessica_biel_03_tn.jpg&quot; title=&quot;images/jessica_biel_03_tn.jpg&quot; onclick=&quot;showImage('images/jessica_biel_03.jpg', 'If you are going to use double-quotes in your text, you need to use the HTML entity &amp;amp;quot;, or your script will &amp;quot;error out&amp;quot;.');&quot; /&gt;
&lt;br /&gt;

&lt;!-- replace your HTML entities! --&gt;
&lt;img src=&quot;images/jessica_biel_07_tn.jpg&quot; alt=&quot;images/jessica_biel_07_tn.jpg&quot; title=&quot;images/jessica_biel_07_tn.jpg&quot; onclick=&quot;showImage('images/jessica_biel_07.jpg', 'In fact, it makes a lot of sense to use entities for everything you include in the call to the showImage function's imgText argument.');&quot; /&gt;
</pre>
<p>And that&#8217;s it. You can see working demos here:</p>
<p><a href="http://www.dougv.com/demo/js_larger_image2/index.html">Single-Page Version</a></p>
<p><a href="http://www.dougv.com/demo/js_larger_image2/iframe.html">Thumbnails In An IFrame Version</a></p>
<p>You can download the code here:</p>
<p><a href='http://www.dougv.com/wp-content/uploads/2008/01/js_larger_image2.zip'>Showing A Larger Image From A Thumbnail OnClick Via JavaScript / DOM Revisited Demo Code</a></p>
<p>I distribute all code under the GNU GPL version 3.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/02/07/showing-a-larger-image-from-a-thumbnail-onclick-via-javascript-dom/" rel="bookmark">Showing A Larger Image From A Thumbnail OnClick Via JavaScript / DOM</a> (88.5)</li>
				<li><a href="https://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/" rel="bookmark">Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM</a> (71.8)</li>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (34.6)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2008/01/28/showing-a-larger-image-from-a-thumbnail-onclick-via-javascript-dom-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Image-Based &#039;Checkbox&#039; Via JavaScript / DOM</title>
		<link>https://www.dougv.com/2007/08/14/an-image-based-checkbox-via-javascript-dom/</link>
		<comments>https://www.dougv.com/2007/08/14/an-image-based-checkbox-via-javascript-dom/#comments</comments>
		<pubDate>Tue, 14 Aug 2007 05:38:03 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/2007/08/14/an-image-based-checkbox-via-javascript-dom/</guid>
		<description><![CDATA[Recently asked on Yahoo! Answers: Use a custom image for check boxes???? Please help, I&#8221;m going insane over such a simple thing.? Heya. Don&#8217;t worry, I&#8217;m not really going insane &#8211; it&#8217;s just kind of frustrating because such a simple little thing is giving me trouble. I want to use custom images for check boxes [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (42.1)</li>
				<li><a href="https://www.dougv.com/2007/01/27/displaying-an-image-on-a-web-page-based-upon-the-current-time-with-javascript-dom/" rel="bookmark">Displaying An Image On A Web Page Based Upon The Current Time With JavaScript / DOM</a> (37.1)</li>
				<li><a href="https://www.dougv.com/2007/01/14/display-a-random-image-with-javascript-dom/" rel="bookmark">Display A Random Image With JavaScript / DOM</a> (29)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>Recently asked on Yahoo! Answers:</p>
<blockquote><p><strong><a href="http://answers.yahoo.com/question/index?qid=20070813203720AAUl7Le">Use a custom image for check boxes???? Please help, I&#8221;m going insane over such a simple thing.?</a></strong></p>
<p>Heya.</p>
<p>Don&#8217;t worry, I&#8217;m not really going insane &#8211; it&#8217;s just kind of frustrating because such a simple little thing is giving me trouble. I want to use custom images for check boxes on a HTML page.</p>
<p>The best way I can describe this is that I want a bright red flashing gif to be there by defualt, then for that to change to a green flashing gif when it&#8217;s clicked.</p>
<p>I don&#8217;t care if it&#8217;s done using a real checkbox, I don&#8217;t need it to actually work. I only need the picture to change when it&#8217;s clicked, and stay changed after that unless clicked again.</p>
<p>Apparently either it&#8217;s such a simple thing to do that no one has ever talked about it, or no one has ever needed to do it before and never given it any thought, because I&#8217;ve looked for help with this all afternoon and tried 6 different ideas of my own with no luck. I can write a fully functional &amp; good looking page in notepad but not get a dumb little image to change when it&#8217;s clicked. Go figure.</p>
<p>Please help! Thank you <img src='https://www.dougv.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p></blockquote>
<p>I&#8217;ve written about using JavaScript / Document Object Model (DOM) manipulation to change images <a href="http://www.dougv.com/2007/02/07/showing-a-larger-image-from-a-thumbnail-onclick-via-javascript-dom/">onclick</a>, <a href="http://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/">onmouseover</a> or via virtually any other event on many occasions. But it&#8217;s the idea of using an image as a checkbox that got me curious: Sure, we can change any image onclick, but can we also get the id attributes of all the checked items for use in form processing?</p>
<p>Yes, we can! So we&#8217;ll tackle this question in three parts: Example 1 will simply change images on click; Example 2 will let us find out which images are &#8220;checked,&#8221; via a JavaScript array; and Example 3 will assign the checked images to regular, old HTML check boxes, so you can process the form as you would via any HTML postback.</p>
<p>As always, I will provide links to working demos at the end of each example.</p>
<p><span id="more-269"></span></p>
<p><strong>Example 1: Change Image On Click</strong></p>
<p>The basic request from the questioner only requires us to change an image any time an item is clicked. For that, we can use a variation on the image-swapping functions I have previously discussed.</p>
<p><strong>Step 1: Prepare The HTML</strong></p>
<p>First up, let&#8217;s prep each IMG tag for image swapping. Again, we need to add two essential attributes to each IMG tag we want to have take a new source: a unique ID for the image, and an onclick event handler. In this case, we&#8217;ll call a function named swapImage, that takes as its argument the ID for this image.</p>
<pre lang="xml"><img id="item1" onclick="swapImage('item1')" src="images/1.jpg" alt="" /></pre>
<p>I&#8217;m also going to add an onclick event to each &#8220;label&#8221; for each of the image &#8220;checkboxes.&#8221; In HTML, if you click on a LABEL element, it will toggle, or give focus to, the element to which it is tied.</p>
<p>In DOM, you can click on any element and it will fire the onclick event. So, if I assign an onclick event handler to text associated with an image, I can make that text behave as though it were a LABEL for the image-based &#8220;checkbox.&#8221; Neat, eh?</p>
<p>In this example, I&#8217;ve cheated on layout by putting everything in a table, so the TD elements containing my &#8220;labels&#8221; will take the onclick event:</p>
<pre lang="xml">
<td onclick="swapImage('item1')">This is item 1. If you click on the icon to the left, or this text, it will change.</td>
</pre>
<p><strong>Step 2: The swapImage() Function</strong></p>
<p>Again, swapping images is as simple as assigning a new source attribute to the image. In our case, all the &#8220;checkboxes&#8221; will use one of two images: an &#8220;up&#8221; image, which is unchecked; and a &#8220;down&#8221; image, for when the item is checked. Since the image is always the same, we&#8217;ll declare the HTTP relative paths to those images in our function.</p>
<p>Next, we get the image that we want to swap via getElementById, taking the argument our onclick event handler sent to the function.</p>
<p>We assign the current source attribute of that image to a variable named theState. What we&#8217;ll get is the full HTTP path to the image &#8212; that is, http://www.domain.com/images/image.ext &#8212; instead of the HTTP relative path, such as images/image.ext.</p>
<p>So, we simply test to see whether we can find the up-state (not-checked) image in theState. If we can, we know the &#8220;checkbox&#8221; was previously unchecked, so we swap the source to be the checked image. If we don&#8217;t find the up-state image in theState, we know the image was &#8220;checked&#8221;, and we swap it back to the unchecked image.</p>
<pre lang="javascript">
function swapImage(imgID) {
	var imgUp = "images/1.jpg";
	var imgDown = "images/2.jpg";

	var theImage = document.getElementById(imgID);
	var theState = theImage.src;

	if(theState.indexOf(imgUp) != -1) {
		theImage.src = imgDown;
	}
	else {
		theImage.src = imgUp;
	}
}
</pre>
<p>And again, I prefer to preload images, so I add my stock preloading function to the page source:</p>
<pre lang="javascript">function preloadImages() {
	for(var i = 0; i < arguments.length; i++) {
		var tmp = new Image();
		tmp.src = arguments[i];
	}
}
</pre>
<p>And add the script to the onload event handler for the BODY tag:</p>
<pre lang="xml"><body onload="preloadImages('images/2.jpg');"></pre>
<p>And it's as simple as that. You can see a working demo here:</p>
<p><a href="http://www.dougv.com/demo/js_imgswap_checked/">http://www.dougv.com/demo/js_imgswap_checked/</a></p>
<p><strong>Example 2: Get The "Checked" Values</strong></p>
<p>While the previous example answers the question posed, it's not as functional as knowing which images have been "checked" -- information we might need to know in order to process a form.</p>
<p>Fortunately, by using getElementsByName, we can retrieve all of our pseudo-checkboxes, iterate through them, discover which are "checked" on the basis of their current source attributes, and add those checked items to an array -- the same way HTML checkboxes return which items are checked.</p>
<p><strong>Step 1: The HTML Modifications</strong></p>
<p>The HTML for Example 2 is nearly the same as the HTML for Example 1, except that for each "checkbox" image, we add a name attribute that is the same for each image -- the same way we would give the same name to all the HTML checkboxes we want grouped together.</p>
<pre lang="xml">
<img id="item1" onclick="swapImage('item1')" src="images/1.jpg" alt="" />
<img id="item2" onclick="swapImage('item2')" src="images/1.jpg" alt="" />
<img id="item3" onclick="swapImage('item3')" src="images/1.jpg" alt="" />
<img id="item4" onclick="swapImage('item4')" src="images/1.jpg" alt="" />
<img id="item5" onclick="swapImage('item5')" src="images/1.jpg" alt="" />
<img id="item6" onclick="swapImage('item6')" src="images/1.jpg" alt="" />
</pre>
<p>For the purpose of this demo, I also add a DIV that will display which items are checked.</p>
<pre lang="xml">
<div id="statusDiv">The following items are checked: none</div>
</pre>
<p>We recycle the same preloader function and body onload event handler call.</p>
<p><strong>Step 2: Set Global JavaScript Variables</strong></p>
<p>We modify the JavaScript by making the up-state and down-state image paths global variables. We also declare, as a global variable, the array which will hold the checked items.</p>
<pre lang="javascript">
var imgUp = "images/1.jpg";
var imgDown = "images/2.jpg";
var checkedItems = new Array();
</pre>
<p><strong>Step 3: Add The getCheckedElements() Function To The swapImage() Function</strong></p>
<p>By virtue of declaring the up-state and down-state images globally, we can remove those declarations from swapImage().</p>
<p>Instead, we'll add to swapImage() a call to a new function, which we will call getCheckedElements(). We do that because every time we check an image on or off, we need to get a new listing of the checked items; so, since the swapImage() function is handling each click for us, it makes sense to call the new function there.</p>
<pre lang="javascript">
function swapImage(imgID) {
	var theImage = document.getElementById(imgID);
	var theState = theImage.src;

	if(theState.indexOf(imgUp) != -1) {
		theImage.src = imgDown;
	}
	else {
		theImage.src = imgUp;
	}
	getCheckedElements();
}
</pre>
<p><strong>Step 4: The getCheckedElements() Function</strong></p>
<p>The function that will tell us which images are "checked" begins by getting all the similarly named images via getElementsByName. That built-in function returns the images as an array. It generally places those items into the array in the order they appear in source code, but not always; so, be cognizant that your items might not be ordered the way you expect.</p>
<p>Next, we reset the length of the checkedItems array to 0, effectively clearing all current values.</p>
<p>Now, we iterate through all the check-images, looking at their source attributes. If the down-state (checked) image is the source, then the item is checked, and we add that check-image's unique ID to the end of the checkedItems array. In effect, the image's unique ID attribute acts as the value of the "checkbox."</p>
<p>At this point, we now have populated the global checkedItems array with all the checked images; we can go ahead and use that however we want.</p>
<p>For this example, I'm just going to echo out all the checked items to a string, which I will then set as the innerHTML of the status DIV I created back in Step 1. You can safely delete that from the function if all you want is for the images to swap.</p>
<pre lang="javascript">
function getCheckedElements() {
	var imgArray = document.getElementsByName('checkboximg');
	checkedItems.length = 0;

	for(var i = 0; i < imgArray.length; i++) {
		var tmp = imgArray[i].src.toString();
		if(tmp.indexOf(imgDown) != -1) {
			checkedItems.push(imgArray[i].id.toString());
		}
	}

	var strOut = "

The following items are checked: ";
	if(checkedItems.length != 0) {
		strOut += checkedItems.toString();
	}
	else {
		strOut += "none";
	}
	strOut += "

";

	var theDiv = document.getElementById('statusDiv');
	theDiv.innerHTML = strOut
}
</pre>
<p>And that's all there is to it! You can see a working demo here:</p>
<p><a href="http://www.dougv.com/demo/js_imgswap_checked/example2.html">http://www.dougv.com/demo/js_imgswap_checked/example2.html</a></p>
<p><strong>Example 3: Assign The Checked Images To HTML Checkboxes</strong></p>
<p>The problem with having the "checked" images stored as a JavaScript array is that unless you intend to use JavaScript to post the checked images to a server via an AJAX request or the like, it's not very handy. It would be far more convenient for us to be able to send the results to our server-side processing page (such as a PHP or ASP.NET script) as standard HTML elements.</p>
<p>We can do that by dynamically adding to the page new HTML checkboxes for each checked image to the form; to me, that's overkill. It's far easier to actually add an HTML checkbox for each check-image, and simply hide those boxes from the user via CSS.</p>
<p>Then, every time we click an image, we'll iterate through the checkedItems array, checking each HTML checkbox that has a corresponding checked image.</p>
<p>And just to prove I'm doing the server-side processing via a regular HTML POST, I'll create a seperate PHP page that will echo back which images -- now, converted to checkboxes -- were checked.</p>
<p><strong>Step 1: Add The HTML Checkboxes</strong></p>
<p>Again, for each image that we can check, we'll add a regular HTML checkbox with the same value as the ID for the image.</p>
<pre lang="xml">
<input lang="hide" name="cblist[]" type="checkbox" value="item1" />
<input lang="hide" name="cblist[]" type="checkbox" value="item2" />
<input lang="hide" name="cblist[]" type="checkbox" value="item3" />
<input lang="hide" name="cblist[]" type="checkbox" value="item4" />
<input lang="hide" name="cblist[]" type="checkbox" value="item5" />
<input lang="hide" name="cblist[]" type="checkbox" value="item6" />
</pre>
<p>Notice that each checkbox has the class "hide" associated with it. That CSS class simply sets the display for the items to none.</p>
<pre lang="css">input.hide {
	display: none;
}
</pre>
<p><strong>Step 2: Modify The getCheckedElements() JavaScript Action</strong></p>
<p>The getCheckedElements() function is modified by replacing our previous text output routine with a new routine that gets all our hidden checkboxes via getElementsByName. Then, it unchecks all the elements, so we start with a clean slate.</p>
<p>We then see if the value of each checkbox corresponds to one of the checkedItems array cells; if so, we set that checkbox's state to checked.</p>
<pre lang="javascript">
function getCheckedElements() {
	var imgArray = document.getElementsByName('checkboximg');
	checkedItems.length = 0;

	for(var i = 0; i < imgArray.length; i++) {
		var tmp = imgArray[i].src.toString();
		if(tmp.indexOf(imgDown) != -1) {
			checkedItems.push(imgArray[i].id.toString());
		}
	}

	var theBoxes = document.getElementsByName('cblist[]');
	for(var i = 0; i < theBoxes.length; i++) {
		theBoxes[i].checked = false;
		for(var x = 0; x < checkedItems.length; x++) {
			if(theBoxes[i].value == checkedItems[x]) {
				theBoxes[i].checked = true;
				break;
			}
		}
	}
}
</pre>
<p><strong>Step 3: Add A Form Action And Submit Button</strong></p>
<p>We assign our soon-to-be-described PHP handler page, echo.php, to the form's action, and add a submit button to our form.</p>
<pre lang="xml">
<form id="frmMain" method="post" action="echo.php">
<table lang="theForm" cellspacing="0">
<tr>
<td><img src="images/1.jpg" id="item1" name="checkboximg" alt="" onclick="swapImage('item1')" /></td>
<td onclick="swapImage('item1')">This is item 1. If you click on the icon to the left, or this text, it will change.</td>
</tr>
<tr>
<td><img src="images/1.jpg" id="item2" name="checkboximg" alt="" onclick="swapImage('item2')" /></td>
<td onclick="swapImage('item2')">This is item 2. If you click on the icon to the left, or this text, it will change.</td>
</tr>
<tr>
<td><img src="images/1.jpg" id="item3" name="checkboximg" alt="" onclick="swapImage('item3')" /></td>
<td onclick="swapImage('item3')">This is item 3. If you click on the icon to the left, or this text, it will change.</td>
</tr>
<tr>
<td><img src="images/1.jpg" id="item4" name="checkboximg" alt="" onclick="swapImage('item4')" /></td>
<td onclick="swapImage('item4')">This is item 4. If you click on the icon to the left, or this text, it will change.</td>
</tr>
<tr>
<td><img src="images/1.jpg" id="item5" name="checkboximg" alt="" onclick="swapImage('item5')" /></td>
<td onclick="swapImage('item5')">This is item 5. If you click on the icon to the left, or this text, it will change.</td>
</tr>
<tr>
<td><img src="images/1.jpg" id="item6" name="checkboximg" alt="" onclick="swapImage('item6')" /></td>
<td onclick="swapImage('item6')">This is item 6. If you click on the icon to the left, or this text, it will change.</td>
</tr>
</table>
<input name="cblist[]" type="checkbox" value="item1" lang="hide" />
<input name="cblist[]" type="checkbox" value="item2" lang="hide" />
<input name="cblist[]" type="checkbox" value="item3" lang="hide" />
<input name="cblist[]" type="checkbox" value="item4" lang="hide" />
<input name="cblist[]" type="checkbox" value="item5" lang="hide" />
<input name="cblist[]" type="checkbox" value="item6" lang="hide" />

Click the submit button to pass the checked items to a PHP page via standard HTML:
<input name="submit" type="submit" value="Submit" />
</form>
</pre>
<p><strong>Step 4: The echo.php Page</strong></p>
<p>The PHP page just needs to echo out any of the checked box values. I'll first check to see if this page has been reached by post.</p>
<p>Then, I check the length of the checkboxes array. If the length is 0, I know nothing was checked and post that; otherwise, I use a foreach() statement to echo out the checked items.</p>
<pre lang="php">
if(isset($_POST['submit']) &#038;&#038; strpos($_SERVER['HTTP_REFERER'], 'dougv.com') !== false) {
	if(count($_POST['cblist']) > 0) {
		echo "

You have checked the following items:

n";
		echo "
<ul>n";
		foreach($_POST['cblist'] as $item) {
			echo "
<li>$item</li>

n";
		}
		echo "</ul>

n";
	}
	else {
		echo "

There are no checked items.

n";
	}
}
else {
	echo "

You didn't post to this page from the example page. Please try again.

n";
}
</pre>
<p>And that's all there is to that. You can see a working demo here:</p>
<p><a href="http://www.dougv.com/demo/js_imgswap_checked/example3.html">http://www.dougv.com/demo/js_imgswap_checked/example3.html</a></p>
<p>I distribute code under the GNU GPL version 3.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (42.1)</li>
				<li><a href="https://www.dougv.com/2007/01/27/displaying-an-image-on-a-web-page-based-upon-the-current-time-with-javascript-dom/" rel="bookmark">Displaying An Image On A Web Page Based Upon The Current Time With JavaScript / DOM</a> (37.1)</li>
				<li><a href="https://www.dougv.com/2007/01/14/display-a-random-image-with-javascript-dom/" rel="bookmark">Display A Random Image With JavaScript / DOM</a> (29)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2007/08/14/an-image-based-checkbox-via-javascript-dom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Swapping An Image From A Non-Animated GIF To An Animated GIF Via JavaScript / DOM</title>
		<link>https://www.dougv.com/2007/08/08/swapping-an-image-from-a-non-animated-gif-to-an-animated-gif-via-javascript-dom/</link>
		<comments>https://www.dougv.com/2007/08/08/swapping-an-image-from-a-non-animated-gif-to-an-animated-gif-via-javascript-dom/#comments</comments>
		<pubDate>Wed, 08 Aug 2007 22:39:35 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/2007/08/08/swapping-an-image-from-a-non-animated-gif-to-an-animated-gif-via-javascript-dom/</guid>
		<description><![CDATA[Recently asked on Yahoo! Answers: I have created a .gif for a webpage how do I get it to animate only when the mouse pointer is on top of it? I have created a .gif for a webpage how do I get it to animate only when the mouse pointer is on top of it? [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (32.8)</li>
				<li><a href="https://www.dougv.com/2007/01/14/display-a-random-image-with-javascript-dom/" rel="bookmark">Display A Random Image With JavaScript / DOM</a> (30.6)</li>
				<li><a href="https://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/" rel="bookmark">Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM</a> (29.8)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>Recently asked on Yahoo! Answers:</p>
<blockquote><p><strong><a href="http://answers.yahoo.com/question/index?qid=20070808123832AAeMjM8">I have created a .gif for a webpage how do I get it to animate only when the mouse pointer is on top of it?</a></strong></p>
<p>I have created a .gif for a webpage how do I get it to animate only when the mouse pointer is on top of it?</p>
<p>Do you have a link to a page which can guide me here.</p>
<p>I have frontpage etc</p></blockquote>
<p>This is fundamentally a mash-up of <a href="http://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/">previous topics</a> I have posted on swapping images on mouseover. Basically, it&#8217;s three steps:</p>
<ul>
<li>Create the animated GIF;</li>
<li>Create a second GIF, that is only the first frame of the animated GIF;</li>
<li>Put together some JavaScript and HTML that swaps the images on mouseover / mouseout.</li>
</ul>
<p>Or, we could simply let JavaScript handle the animations, and just use a series of images in sequence. I&#8217;ll demonstrate both approaches. As always, a link to a functioning demo appears at the end of this entry.</p>
<p><span id="more-268"></span></p>
<h3>Step 1: The Basic Image Swap JavaScript Functions</h3>
<p>Swapping an image in JavaScript / DOM manipulation is simple: We simply have JavaScript change the src (source) attribute of the given image.</p>
<p>To do that, we need to know two things: the ID of the image we want to change, and the new source for the image.</p>
<p>We pass those as arguments to the script, which first gets the image we want to change via getElementById, then assigns that image a new src based on the second argument.</p>
<pre class="brush: jscript; title: ; notranslate">
function swapImage(imgID, imgSrc) {
	var theImage = document.getElementById(imgID)
	theImage.src = imgSrc;
}
</pre>
<p>Yes, it&#8217;s that simple.</p>
<p>But as I&#8217;ve previously noted, unless you pre-load the image(s) you&#8217;re going to use on the mouseover, there will be a delay between the mouseover and when the new image appears. To resolve that problem, we create a preload script that accepts a list of image paths, and loads them all into the page cache without actually displaying them.</p>
<p>Notice that we don&#8217;t need to explicitly state all the parameters we&#8217;re going to pass to this function. In JavaScript, arguments to a function can be called as an array, meaning you don&#8217;t need to know how many arguments there are, or what those arguments are (objects, strings, integers, etc.), in order to work with all of them; we can simply iterate through the arguments as we would any array.</p>
<pre class="brush: jscript; title: ; notranslate">
function preLoadImages() {
	for(var i = 0; i &lt; arguments.length; i++) {
		var tmpImage = new Image();
		tmpImage.src = arguments[i];
	}
}
</pre>
<h3>Step 2: Prepare The HTML For Swapping</h3>
<p>The HTML we use to make the image swap needs three elements:</p>
<ul>
<li>A unique ID for the image, so the JavaScript function knows to swap this image;</li>
<li>A mouseover event handler that will call the swapImage function and replace the default image with our animated GIF;</li>
<li>A mouseout event handler that will call the swapImage function again, replacing the animated GIF with the default image.</li>
</ul>
<p>So, here&#8217;s how our IMG tag will look with all those attributes added:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;img id=&quot;imgToSwap&quot; src=&quot;elena.gif&quot; alt=&quot;animated gif&quot; onmouseover=&quot;swapImage('imgToSwap', 'elena-animated.gif');&quot; onmouseout=&quot;swapImage('imgToSwap', 'elena.gif');&quot; /&gt;
</pre>
<p>Notice that the image&#8217;s initial src attribute is set to be the non-animated image.</p>
<p>We also need to add the preload function to the body&#8217;s onload event handler. Again, we add as arguments all the animated GIFs our page will use as swaps:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;body onload=&quot;preLoadImages('elena-animated.gif');&quot;&gt;
</pre>
<p>And that&#8217;s all there is to it. You can see this in action here:</p>
<p><a href="http://www.dougv.com/demo/js_animated_imgswap/">http://www.dougv.com/demo/js_animated_imgswap/</a></p>
<p>To use it, simply download the page to your computer and copy and paste the JavaScript to your page.</p>
<h3>Example 2: A JavaScript / DOM Animated Sequence That Stops On MouseOut</h3>
<p>The problem with the previous example, as you may have noted, is that when you mouse out, you go back to the first frame &#8212; which comes off as somewhat abrupt. How can we fix that so that the animation stops when we mouse out but resumes from the last frame when we mouse over again?</p>
<p>Simple: We&#8217;ll let JavaScript do the animating for us, by using setTimeout to continuously change the source of the image in the same sequence as the individual frames of the animation. And, as an added benefit, we can use JPGs or PNGs for this method &#8212; in effect, making animated JPGs or animated PNGs!</p>
<h3>Step 1: Some Global Variables</h3>
<p>We need two global variables to make this script work: an array to hold all of our animation images, in order; and an integer that will store the current index of the array &#8212; that is, the number of the array cell that is the source of the image at the moment.</p>
<pre class="brush: jscript; title: ; notranslate">
var imgArray = new Array();
var imgIndex = 0;
</pre>
<h3>Step 2: The JavaScript Image Preload Script Revisted</h3>
<p>We&#8217;ll again use a preloader for this script, but we&#8217;ll also populate the global array with it. So, when we write the BODY tag&#8217;s onload event handler, we&#8217;ll put in the names of our animation images, in the order they should appear in the animation (that is, frame 1 first; frame 2 second, etc.).</p>
<pre class="brush: jscript; title: ; notranslate">
function pageLoad() {
	for(var i = 0; i &lt; arguments.length; i++) {
		imgArray[i] = arguments[i];
		var tmp = new Image();
		tmp.src = arguments[i];
	}
}
</pre>
<h3>Step 3: The Animation Function</h3>
<p>To animate our JPGs, we simply get the image via getElementById, then assign it a new src attribute from the global array. We then increment the index counter by one, and reset it back to 0 if that index goes out of range.</p>
<p>Finally, we use setTimeout to call the script over and over again; in our case, we&#8217;ll change images every half-second.</p>
<pre class="brush: jscript; title: ; notranslate">
function animate() {
	var theImage = document.getElementById('imgToSwap');
	theImage.src = imgArray[imgIndex];
	imgIndex = imgIndex + 1;

	if(imgIndex == imgArray.length) {
		imgIndex = 0;
	}
	timerID = setTimeout('animate()', 500);
}
</pre>
<h3>Step 4: The Stop Function</h3>
<p>Finally, we need a way to stop the images from changing; that&#8217;s as simple as calling clearTimeout on the timer we created in the animate() function.</p>
<pre class="brush: jscript; title: ; notranslate">
function stop() {
	clearTimeout(timerID);
}
</pre>
<h3>Step 5: The HTML</h3>
<p>Two quick HTML tag changes make everything work. First, we add the images to the pageLoad function&#8217;s arguments, and call that from the onload event of the BODY tag.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;body onload=&quot;pageLoad('elena1.jpg', 'elena2.jpg', 'elena3.jpg', 'elena4.jpg', 'elena5.jpg', 'elena6.jpg')&quot;&gt;
</pre>
<p>The IMG tag takes an onmouseover event that calls the animate() function, and an onmouseout event that calls stop().</p>
<pre class="brush: xml; title: ; notranslate">
&lt;img src=&quot;elena1.jpg&quot; alt=&quot;animated gif&quot; id=&quot;imgToSwap&quot; onmouseover=&quot;animate()&quot; onmouseout=&quot;stop()&quot; /&gt;
</pre>
<p>And that&#8217;s all there is to it. You can see a working demo here:</p>
<p><a href="http://www.dougv.com/demo/js_animated_imgswap/example2.html">http://www.dougv.com/demo/js_animated_imgswap/example2.html</a></p>
<p>Again, to use it, just save the page to your computer, copy the JavaScript to your page and change the images as appropriate.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (32.8)</li>
				<li><a href="https://www.dougv.com/2007/01/14/display-a-random-image-with-javascript-dom/" rel="bookmark">Display A Random Image With JavaScript / DOM</a> (30.6)</li>
				<li><a href="https://www.dougv.com/2007/06/14/showing-a-larger-image-on-thumbnail-mouseover-with-javascript-dom/" rel="bookmark">Showing A Larger Image On Thumbnail MouseOver with JavaScript / DOM</a> (29.8)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2007/08/08/swapping-an-image-from-a-non-animated-gif-to-an-animated-gif-via-javascript-dom/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Displaying A Random Image From A Directory Via PHP, Part 2</title>
		<link>https://www.dougv.com/2007/07/03/displaying-a-random-image-from-a-directory-via-php-part-2/</link>
		<comments>https://www.dougv.com/2007/07/03/displaying-a-random-image-from-a-directory-via-php-part-2/#comments</comments>
		<pubDate>Wed, 04 Jul 2007 03:24:28 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>
		<category><![CDATA[file system]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/2007/07/03/displaying-a-random-image-from-a-directory-via-php-part-2/</guid>
		<description><![CDATA[In a recent blog post about randomly displaying an image from a directory via PHP and its built-in image and filesystem functions, I promised to expand upon the answer I had given to demonstrate some other cool filesystem tricks. It&#8217;s about time I made good on that promise. We&#8217;ll start by showing how to display [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/06/27/displaying-a-random-image-from-a-directory-via-php/" rel="bookmark">Displaying A Random Image From A Directory Via PHP</a> (61.1)</li>
				<li><a href="https://www.dougv.com/2007/01/14/display-a-random-image-with-javascript-dom/" rel="bookmark">Display A Random Image With JavaScript / DOM</a> (27.8)</li>
				<li><a href="https://www.dougv.com/2006/12/20/displaying-a-random-yahoo-search-every-30-seconds-with-javascript-and-php/" rel="bookmark">Displaying A Random Yahoo! Search Every 30 Seconds With JavaScript And PHP</a> (25.2)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://www.dougv.com/2007/06/27/displaying-a-random-image-from-a-directory-via-php/">recent blog post</a> about randomly displaying an image from a directory via PHP and its built-in image and filesystem functions, I promised to expand upon the answer I had given to demonstrate some other cool filesystem tricks.</p>
<p>It&#8217;s about time I made good on that promise.</p>
<p>We&#8217;ll start by showing how to display a random image on a Web page, rather than forging the PHP to represent itself as an image; and we&#8217;ll also make a thumbnail gallery of all the images in the folder, which even shows the active image.</p>
<p><span id="more-249"></span></p>
<p><strong>Displaying The Random PHP Image On The Page</strong></p>
<p>The script to randomly select and display an image on a Web page is remarkably similar to the original script in <a href="http://www.dougv.com/2007/06/27/displaying-a-random-image-from-a-directory-via-php/">this post</a>, except that we&#8217;re going to find the image&#8217;s URL to apply as the src attribute for an IMG tag, rather than putting the image directly to the output buffer.</p>
<p>That URL we&#8217;ll store as the variable $img_src:</p>
<pre lang="php">
$img_path = "images/";
$exts = "/(.jpg)|(.jpeg)|(.gif)|(.png)$/i";

if(is_dir($img_path)) {
	$img_handle = opendir($img_path);

	while (false !== ($img_file = readdir($img_handle))) {
		if (preg_match($exts, $img_file)) {
			$img[] = $img_file;
		}
	}

	mt_srand();
	$len = count($img) - 1;
	$index = mt_rand(0, $len);
	$img_src = $img_path . $img[$index];

	closedir($img_handle);
}
else {
	die("no such directory!");
}
</pre>
<p>And now, to display the &#8220;random&#8221; image, we simply echo out $img_src inside an IMG tag:</p>
<pre lang="xml">
<img src="<?php echo $img_src; ?>" alt="<?php echo $img_src; ?>" title="<?php echo $img_src; ?>" />
</pre>
<p><strong>A Thumbnail Gallery That Shows The Current Image</strong></p>
<p>Using the same methods we employed to select a random, full-size image on the page, we can use to display a series of thumbnail images. In fact, we can even combine the scripts, to apply a background color to the thumbnail that is currently being displayed in full size.</p>
<p>We&#8217;ll sort of cheat on layout by using a table to display the thumbnails. (Technically, this can be considered tabular data, but best practices would be to not use a table here).</p>
<pre lang="php">
$i = 0;
$TN_COLS = 3;
$tn_path = "images/tn/";
</pre>
<p>Next, we&#8217;ll use the same method we did above to open the directory and begin iterating through the thumbnails, dumping them into an array as well:</p>
<pre lang="php">
if(is_dir($tn_path)) {
	$tn_handle = opendir($tn_path);

	while(false !== ($tn_file = readdir($tn_handle))) {
		if(preg_match($exts, $tn_file)) {
			$tn_img[] = $tn_file;
		}
	}
</pre>
<p>Now for the first real change: We apply a natsort on the array.</p>
<p>We do that not only because the filesystem stores icons in an unpredictable manner &#8212; that is, any old item in the directory could be listed first in any one iteration of the directory &#8212; but because we want the pictures ordered in a way that makes sense to most people.</p>
<p>Unlike a normal array sort, natsort will sort an array more like a human would. For example, if you have thumbnails named 1.jpg through 15.jpg, a normal array sort would place 11.jpg-15.jpg, after 1.jpg but before 2.jpg. Natsort will put 11.jpg-15.jpg at the end of the array, the way most humans would.</p>
<pre lang="php">
	natsort($tn_img);
</pre>
<p>With the array sorted, we can begin outputting each item in the array as a cell in our table.</p>
<p>We&#8217;re going to dynamically create rows in the table based on the $TN_COLS variable we declared earlier. For example, since we declared 3 as the value of $TN_COLS, any time we have a cell that is divisible by 3, we&#8217;re going to break for a new row.</p>
<p>We&#8217;re also going to see if the thumbnail image we are using is the same as the currently displaying large image. If it is, we apply a class to the table cell; in that class, we define the background color we want to have appear.</p>
<pre lang="php">
	foreach($tn_img as $thumb) {
		if($i % $TN_COLS == 0) {
			echo "
<tr>";
		}

		echo "
<td";
		if($thumb == $img[$index]) {
			echo " lang="active"";
		}
		echo ">";
		echo "<img src="" . $tn_path . $thumb . "" alt="$thumb" title="$thumb" />";
		echo "";
		echo $thumb;
		echo "</td>

n";

		$i++;
		if($i % $TN_COLS == 0) {
			echo "</tr>

n";
		}
	}
</pre>
<p>We have one last housekeeping item: It&#8217;s possible we don&#8217;t have enough cells to complete the last row. To fix that problem, we add another loop that &#8220;pads&#8221; the last row with enough empty cells to complete it.</p>
<pre lang="php">
	if($i % $TN_COLS != 0) {
		for($x = $i; $x % $TN_COLS > 0; $x++) {
			echo "
<td>&nbsp;</td>

n";
		}
		echo "</tr>

n";
	}

	closedir($tn_handle);
}
else {
	die("no such thumbnail image path!");
}
</pre>
<p>You can see this script in action at:</p>
<p><a href="http://www.dougv.com/demo/php_random_image/example2.php">http://www.dougv.com/demo/php_random_image/example2.php</a></p>
<p>You can download this script and its related images from here: <a href='http://www.dougv.com/wp-content/uploads/2007/06/php_random_image.zip'>Displaying A Random Image From A Directory Via PHP Source Code</a></p>
<p>I distribute all code under the GNU GPL 3.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2007/06/27/displaying-a-random-image-from-a-directory-via-php/" rel="bookmark">Displaying A Random Image From A Directory Via PHP</a> (61.1)</li>
				<li><a href="https://www.dougv.com/2007/01/14/display-a-random-image-with-javascript-dom/" rel="bookmark">Display A Random Image With JavaScript / DOM</a> (27.8)</li>
				<li><a href="https://www.dougv.com/2006/12/20/displaying-a-random-yahoo-search-every-30-seconds-with-javascript-and-php/" rel="bookmark">Displaying A Random Yahoo! Search Every 30 Seconds With JavaScript And PHP</a> (25.2)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a>, <a href="https://www.dougv.com/tag/file-system/" title="file system" rel="tag">file system</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2007/07/03/displaying-a-random-image-from-a-directory-via-php-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Displaying A Random Image From A Directory Via PHP</title>
		<link>https://www.dougv.com/2007/06/27/displaying-a-random-image-from-a-directory-via-php/</link>
		<comments>https://www.dougv.com/2007/06/27/displaying-a-random-image-from-a-directory-via-php/#comments</comments>
		<pubDate>Thu, 28 Jun 2007 04:29:21 +0000</pubDate>
		<dc:creator>Doug Vanderweide</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[DOM images]]></category>
		<category><![CDATA[file system]]></category>

		<guid isPermaLink="false">http://www.dougv.com/blog/2007/06/27/displaying-a-random-image-from-a-directory-via-php/</guid>
		<description><![CDATA[Recently asked on Yahoo! Answers: How would one code a rotating image (using PHP) that can be hosted on Geocities Pro for, say, a forum? In the past, I&#8217;ve been able to host a rotating image using another method by naming a folder &#8216;something.png&#8217; to fool a forum into thinking the folder is a picture [...]<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2006/12/20/displaying-a-random-yahoo-search-every-30-seconds-with-javascript-and-php/" rel="bookmark">Displaying A Random Yahoo! Search Every 30 Seconds With JavaScript And PHP</a> (26.1)</li>
				<li><a href="https://www.dougv.com/2007/01/14/display-a-random-image-with-javascript-dom/" rel="bookmark">Display A Random Image With JavaScript / DOM</a> (25.8)</li>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (24.5)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.
	</div>
]]></description>
			<content:encoded><![CDATA[<p>Recently asked on Yahoo! Answers:</p>
<blockquote><p>
<strong><a href="http://answers.yahoo.com/question/index?qid=20070627175856AASRhZe">How would one code a rotating image (using PHP) that can be hosted on Geocities Pro for, say, a forum?</a></strong></p>
<p>In the past, I&#8217;ve been able to host a rotating image using another method by naming a folder &#8216;something.png&#8217; to fool a forum into thinking the folder is a picture and it reads the index.php file, which in turn pulls up one of the images I have coded. Now that I&#8217;m on Geocities Pro, I cannot make such a folder but would like to still use my rotating image. Is there another way I can code this and still be able to use it with forum BBCode?
</p></blockquote>
<p>Basically, this questioner wants a PHP script to look through the contents of an image directory, randomly select one of the images in that directory, and pass the script itself off as the image.</p>
<p>That&#8217;s fairly simple to do in PHP, but it does require a number of steps and a few tricks to overcome some limitations of <a href="http://us2.php.net/manual/en/ref.filesystem.php">PHP&#8217;s built-in filesystem functions</a>.</p>
<p>This question also gives me a chance to explain working with the filesystem in PHP, and to demonstrate how loops and arrays can be used to produce some really neat results, so I&#8217;ll expand on that in a follow-up post.</p>
<p>As always, a working demo and source code will be available for download at the end of this article.</p>
<p><span id="more-245"></span></p>
<p><strong>Step 1: Declare Basic Variables</strong></p>
<p>We&#8217;ll start by declaring two variables:</p>
<ul>
<li>The path, relative to the script, of the folder containing the images we want.</li>
<li>A regular expression that gives us the allowed extensions for our images.</li>
</ul>
<p>For those who are new to the term, a <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> is basically a text pattern you want to find. It uses special characters and syntax to indicate what you want to find; in our case, we&#8217;re going to search for file extensions.</p>
<p>Don&#8217;t worry if you don&#8217;t understand the expression; trust me that this one will allow you to use image files with the extension .jpg, .jpeg, .gif or .png; the test will also be case-insensitive, so .JPG is the same thing as .jpg.</p>
<p>More on all that later. Let&#8217;s look at the opening code.</p>
<pre lang="php">
$img_path = "images/";
$exts = "/(.jpg)|(.jpeg)|(.gif)|(.png)$/i";
</pre>
<p><strong>Step 2: Open The Directory And Iterate Through The Files</strong></p>
<p>Our next step is to make sure the image directory we declared actually exists. If it does, we want to go ahead and open the directory, then begin looking through the files.</p>
<p><strong>An aside on the difference between evaluating equivalence vs. identity:</strong> Notice, in the code below, that we use the identity operator (===), and not the equivalence operator (==), to test whether we have read all the files in the directory.</p>
<p>We do that because, as the PHP documentation notes, <a href="http://us2.php.net/manual/en/function.readdir.php">readdir()</a> may not return a Boolean &#8220;false,&#8221; but may return another value that is the same as false.</p>
<p>The identity operator allows us to compare two variables not on the basis of them having the same value (equivalence), but being the same thing.</p>
<p>If we just use the equivalence operator, and readdir() returns a value that means the same as Boolean false, that won&#8217;t be equal to Boolean false; our loop would continue and we&#8217;d get an error. If we use the identity operator, we know that whatever false value readdir() actually returns, it means the same, for all intents and purposes, as Boolean false; our loop will stop executing. (End of aside.)</p>
<pre lang="php">
if(is_dir($img_path)) {
	//open directory
	$img_handle = opendir($img_path);

	//iterate through all items in directory
	while (false !== ($img_file = readdir($img_handle))) {
</pre>
<p><strong>Step 3: Put All Image Files Into An Array</strong></p>
<p>We&#8217;re going to read the names of all image files into a dynamic array, the reasons for which will be clearer in a moment. For now, you&#8217;ll notice we use preg_match, the preferred method for running a regular expression match against a string, to make sure that the file we&#8217;re currently looking has an extension that&#8217;s in our allowable extensions list.</p>
<p>An added bonus of this approach is that it resolves problems with subdirectories in PHP.</p>
<p>Basically, in PHP, if you are iterating through a directory and it has subdirectories, the built-in functions in PHP will treat all subdirectories as files; you can&#8217;t even evaluate if the subdirectory is a directory.</p>
<p>Needless to say, that&#8217;s a major problem, and the only effective way to work around it, via the filesystem, is to read each &#8220;file,&#8221; then see if trying to enter it, as if it were a directory, works. If so, you&#8217;ve found a subdirectory, not a file.</p>
<p>That&#8217;s pretty wasteful, in my opinion, and possibly dangerous. It makes much more sense, and is far less resource-intensive, to simply look at the name of the file and see if it matches the kind of file we want.</p>
<p>Note that not all Web hosts will have compiled support for Perl-Compatible Regular Expressions (<a href="http://us2.php.net/manual/en/ref.pcre.php">PCRE</a>). Virtually all do, but yours may not have; if not, this script won&#8217;t be of much use to you.</p>
<p>Lastly, once we&#8217;re done looping through the files in the directory, we want to close the directory to free up the considerable resources PHP uses to work with the filesystem.</p>
<pre lang="php">
if (preg_match($exts, $img_file)) {
	$img[] = $img_file;
}

closedir($img_handle);
</pre>
<p><strong>Step 4: Select The Random Image Via A Random Number</strong></p>
<p>Here&#8217;s the magic: Since we&#8217;ve dumped all the file names into an array, all we need to do is randomly generate an index number, and pull out from the array the name of the file that is at that index.</p>
<p>So, our task list for this step is:</p>
<ul>
<li>Initialize our random number generator;</li>
<li>Get the total number of items in the array and subtract one, which will give us the index of the last item in the array. If there are no items in the array, we&#8217;ll die and report that fact;</li>
<li>Generate a random number between 0 and the integer we get from the step above, which gives us a random index for the array;</li>
<li>Append the file path to the array cell contents at the index we generated, which gives us a full file path to one of the images in the directory.</li>
</ul>
<pre lang="php">
mt_srand();

if(count($img) == 0) {
	die("no images in image directory");
}
else {
	$len = count($img) - 1;
}

$index = mt_rand(0, $len);
$img_src = $img_path . $img[$index];
</pre>
<p><strong>Step 5: Get The Content-Type</strong></p>
<p>The way we&#8217;re going to make this PHP script act like an image is by forging the HTTP header&#8217;s <a href="http://en.wikipedia.org/wiki/Internet_media_type">content-type</a> value. Instead of outputting &#8220;text/html&#8221;, which Web pages send, we&#8217;ll send one of the image types, depending on our file&#8217;s extension.</p>
<p>So first, we need to get the extension from our file.</p>
<ul>
<li>We set the basic part of the content-type string as a variable.</li>
<li>We split the file&#8217;s name into an array, around the periods.</li>
<li>We then remove the last item of the array, which will contain our extension. We know that because by virtue of the regular expression we used to sort files earlier, we know all files will end with one of our four image file extensions.</li>
<li>We cast the extension down to lower-case, to make sure we get a case-insensitive match.</li>
<li>We run the extension through a switch that assumes the file is a JPEG, but changes the content-type to GIF or PNG if that&#8217;s what we actually have.</li>
</ul>
<pre lang="php">
$ct = "Content-type: image/";

$temp = explode(".", $img_src);
$temp = array_pop($temp);
$temp = strtolower($temp);

switch($temp) {
	case "png":
		$ct .= "png";
		break;
	case "gif":
		$ct .= "gif";
		break;
	default:
		$ct .= "jpeg";
}
</pre>
<p><strong>Step 6: Echo Out The Forged Header And The Image</strong></p>
<p>Outputting our image is as simple as sending the forged header (via the cleverly-named header() function) and then dumping the image file&#8217;s contents directly to the output buffer via readfile().</p>
<pre lang="php">
header($ct);
readfile($img_src);
</pre>
<p>And, as a final step, we&#8217;ll add an else statement to the opening if statement; if the path we specified in Step 1 doesn&#8217;t lead to a directory, we&#8217;ll die the script and report that.</p>
<pre lang="php">
else {
	die("no such directory!");
}
</pre>
<p>And that&#8217;s all there is to it. You can see the script in action here:</p>
<p><a href="http://www.dougv.com/demo/php_random_image/index.php">http://www.dougv.com/demo/php_random_image/index.php</a></p>
<p>Just reload the page to see a different image.</p>
<p><strong>A final aside on randomness: </strong>When selecting a random number, the larger the range, the more random the number. Thus, the more images that act as a source for this script, the more random your results. I&#8217;m using 15 images. (End of aside.)</p>
<p>You can download the source code here: <a href='http://www.dougv.com/wp-content/uploads/2007/06/php_random_image.zip'>Displaying A Random Image From A Directory Via PHP Source Code</a></p>
<p>I distribute all code under the GNU GPL 3.</p>
<div class="yarpp">
	<h5>Related Posts</h5>
		<ol>
				<li><a href="https://www.dougv.com/2006/12/20/displaying-a-random-yahoo-search-every-30-seconds-with-javascript-and-php/" rel="bookmark">Displaying A Random Yahoo! Search Every 30 Seconds With JavaScript And PHP</a> (26.1)</li>
				<li><a href="https://www.dougv.com/2007/01/14/display-a-random-image-with-javascript-dom/" rel="bookmark">Display A Random Image With JavaScript / DOM</a> (25.8)</li>
				<li><a href="https://www.dougv.com/2007/01/09/displaying-a-new-image-based-on-image-choices-via-checkboxes-the-html-dom-and-javascript/" rel="bookmark">Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript</a> (24.5)</li>
			</ol>
	<p class="note">The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.</p>
	</div>

	Tags: <a href="https://www.dougv.com/tag/dom-images/" title="DOM images" rel="tag">DOM images</a>, <a href="https://www.dougv.com/tag/file-system/" title="file system" rel="tag">file system</a><br />
]]></content:encoded>
			<wfw:commentRss>https://www.dougv.com/2007/06/27/displaying-a-random-image-from-a-directory-via-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

