<?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>Trevor Davis &#187; Tutorial</title>
	<atom:link href="http://trevordavis.net/category/blog/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://trevordavis.net</link>
	<description>Doing That Web Standards Thing</description>
	<lastBuildDate>Fri, 12 Feb 2010 14:05:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<atom:link rel='hub' href='http://trevordavis.net/?pushpress=hub'/>
<cloud domain='trevordavis.net' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
		<item>
		<title>Freeform + FieldFrame = ExpressionEngine Form Builder</title>
		<link>http://trevordavis.net/blog/tutorial/freeform-fieldframe-expressionengine-form-builder/</link>
		<comments>http://trevordavis.net/blog/tutorial/freeform-fieldframe-expressionengine-form-builder/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 06:38:49 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=2224</guid>
		<description><![CDATA[A form builder is a regular request for some clients when they are looking for a content management system. There aren&#8217;t that many CMS that have this kind of functionality built-in, and even if they do, the implementation is usually less than desirable.
If you follow along with what I&#8217;ve been up to, you can probably [...]]]></description>
			<content:encoded><![CDATA[<p>A form builder is a regular request for some clients when they are looking for a content management system. There aren&rsquo;t that many CMS that have this kind of functionality built-in, and even if they do, the implementation is usually less than desirable.</p>
<p>If you follow along with what I&rsquo;ve been up to, you can probably tell that I have been on a big <a href="http://expressionengine.com/">ExpressionEngine</a> kick. I&rsquo;ve been using it on a ton of projects recently, and I love it for its flexibility. Although it does lack a true form builder, I figured out a simple way to build one.</p>
<p><span id="more-2224"></span></p>
<p>If you are impatient and just want to get to the <a href="http://ee.trevordavis.net/forms/contact-form/">demo</a>, go ahead. Although the form will look like nothing special, as I have just added some simple styling. The real magic of the form builder happens in the Control Panel.</p>
<h2>We Need Add-ons</h2>
<p>This form builder would not be possible without the use of some awesome add-ons:</p>
<ul>
<li><a href="http://devot-ee.com/add-ons/extensions/fieldframe/"><strong>FieldFrame</strong></a>
<p>This one is a no-brainer. I can&rsquo;t even imagine building a site without it.</p>
</li>
<li><a href="http://devot-ee.com/add-ons/modules/freeform/"><strong>Freeform</strong></a>
<p>If you need a form in EE, this is the way to do it.</p>
</li>
<li><a href="http://devot-ee.com/add-ons/extensions/freeform-data-select/"><strong>Freeform Data Select</strong></a>
<p>A new fieldtype which pulls in templates and fields from the Freeform module.</p>
</li>
</ul>
<h2>Creating a Field Group</h2>
<p>I built a custom Field Group called Forms, which consisted of four fields:</p>
<ul>
<li>Template</li>
<li>Notification Email Addresses</li>
<li>Return Page</li>
<li>Fields</li>
</ul>
<p>The first three are pretty simple, so I will just give a quick run through on the specifications for those fields and give a more detail review of the <strong>Fields</strong> field:</p>
<h3>Template</h3>
<p>This is where you select the Freeform template that will be used for the email. This field is not completely necessary, as just using the default template should be good enough, but I figured since it was an option, to throw it in.</p>
<ul>
<li><strong>Field Name</strong>: form_template</li>
<li><strong>Field Type</strong>: Freeform Data Select</li>
<li><strong>Populate drop-down with</strong>: Freeform Templates</li>
</ul>
<h3>Notification Email Addresses</h3>
<p>This is where you will enter the email address(es) that you want to email when the form is submitted. Since Freeform wants multiple email addresses separated by the | character, I added some help text describing that as well.</p>
<ul>
<li><strong>Field Name</strong>: form_notify</li>
<li><strong>Field Type</strong>: Text Input</li>
<li><strong>Default Text Formatting for This Field</strong>: None</li>
<li><strong>Hide Formatting Menu</strong></li>
</ul>
<h3>Return Page</h3>
<p>This is where you enter the URL to the thank you page. Once a user successfully submits the form, they will be redirected here.</p>
<ul>
<li><strong>Field Name</strong>: form_return</li>
<li><strong>Field Type</strong>: Text Input</li>
<li><strong>Default Text Formatting for This Field</strong>: None</li>
<li><strong>Hide Formatting Menu</strong></li>
</ul>
<h3>Fields</h3>
<p>This is where the magic happens. This field is a FF Matrix field type that consists of five other fields. Each row of the FF Matrix represents one field (or field group) in the form. I&rsquo;ll give a brief description of each field of the FF Matrix and show you a screenshot so you can get a better picture:</p>
<ul>
<li><strong>Field Name</strong>: form_field</li>
<li><strong>Field Type</strong>: FF Matrix</li>
</ul>
<h4>Label</h4>
<p>This is where you will enter the label for the form field:</p>
<ul>
<li><strong>Col Name</strong>: label</li>
<li><strong>Cell Type</strong>: Text Input</li>
</ul>
<h4>Field</h4>
<p>This field pulls in all of the fields that have been entered into the Freeform module. So you are presented with a dropdown of all of the fields, and you just select the appropriate one:</p>
<ul>
<li><strong>Col Name</strong>: field</li>
<li><strong>Cell Type</strong>: Freeform Data Select</li>
<li><strong>Populate drop-down with</strong>: Freeform fields</li>
</ul>
<h4>Field Type</h4>
<p>This is where you select the type of form field you want to use. I put in a few different options, but this could be expanded upon too:</p>
<ul>
<li><strong>Col Name</strong>: type</li>
<li><strong>Cell Type</strong>: FF Select</li>
<li><strong>Select Options</strong>: Text Input<br />
		Textarea<br />
		Select<br />
		Multi-select<br />
		Checkbox<br />
		Checkbox Group<br />
		Radio Group
	</li>
</ul>
<h4>Is this field required?</h4>
<p>With most forms, there are some fields that are required and some that are not. If you want the field to be required, you just check the checkbox and the Freeform module will make sure it is filled in:</p>
<ul>
<li><strong>Col Name</strong>: required</li>
<li><strong>Cell Type</strong>: FF Checkbox</li>
<li><strong>Checkbox Label</strong>: Is this field required?</li>
</ul>
<h4>Options</h4>
<p>Finally, this field is used when you select a field type that has multiple options. For example, if you select a &ldquo;Select&rdquo; field type, you need to provide the options to populate it. So you enter the options separated by the | character:</p>
<ul>
<li><strong>Col Name</strong>: options</li>
<li><strong>Cell Type</strong>: Text Input</li>
</ul>
<p><a href="http://trevordavis.net/wp-content/uploads/2009/11/ff-matrix.png" title="FieldFrame Matrix Configuration" rel="lightbox"><img src="http://trevordavis.net/wp-content/uploads/2009/11/ff-matrix_thumb.png" alt="FieldFrame Matrix Configuration" width="570" height="203" class="pullLeft frame" /></a></p>
<p>So that is all you need for the Field Group, now go ahead and create a Forms Channel (or Weblog) and make sure to assign the Forms Field Group to it.</p>
<p>Now, when you go to publish a Forms entry, you should see something like this:</p>
<p><a href="http://trevordavis.net/wp-content/uploads/2009/11/form-entry.png" rel="lightbox" title="New Forms Entry"><img src="http://trevordavis.net/wp-content/uploads/2009/11/form-entry_thumb.png" alt="New Forms Entry" width="570" height="258" class="pullLeft frame" /></a></p>
<p>I made a <a href="http://ee.trevordavis.net/forms/contact-form/">demo form</a> showing off the various types of form fields. Here is what that entry looks like in the Control Panel:</p>
<p><a href="http://trevordavis.net/wp-content/uploads/2009/11/demo-entry.png" rel="lightbox" title="Demo Form Entry in Control Panel"><img src="http://trevordavis.net/wp-content/uploads/2009/11/demo-entry_thumb.png" alt="Demo Form Entry in Control Panel" width="570" height="400" class="pullLeft frame" /></a></p>
<h2>Template</h2>
<p>Now that we have our Channel and Field Group all setup, we need to deal with the template. You could really setup your template/template group in various ways, so I&rsquo;m not going to get into those details. One detail that you need to know is that <strong>I enabled PHP for my template</strong>.</p>
<p>First, we just need to start with a simple <strong>exp:weblog:entries</strong> tag:</p>
<pre><code>{exp:weblog:entries weblog="forms" limit="1" disable="categories|category_fields|member_data|pagination|trackbacks"}
&hellip;
{/exp:weblog:entries}</code></pre>
<p>Next, we want to start the Freeform form tag:</p>
<pre><code>{exp:weblog:entries weblog="forms" limit="1" disable="categories|category_fields|member_data|pagination|trackbacks"}
	{exp:freeform:form form_name="{url_title}" form_id="{url_title}" template="{form_template}" notify="{form_notify}" return="{form_return}"}
	&hellip;
	{/exp:freeform:form}
{/exp:weblog:entries}</code></pre>
<p>Since we are inside of the exp:weblog:entries tag, we have access to everything that is being returned from that entry. If you have any questions about the various parameters, <a href="http://www.solspace.com/docs/detail/freeform_form/#parameters">refer to the Freeform Documentation</a>.</p>
<p>So far, the values that we are passing into the parameters are pretty straightforward, just custom fields from our entry. But, passing in the <a href="http://www.solspace.com/docs/detail/freeform_form/#required">required</a> parameter is a little more challenging, since we have to loop through all of the rows in our FF Matrix.</p>
<p>If we <a href="http://brandon-kelly.com/fieldframe/docs/ff-matrix">refer to the FF Matrix documentation</a>, we can see how to loop through the rows in the matrix. I only want to return rows that have the required checkbox checked, and I want to separate the names of the fields with the | character. Then, I use the backspace parameter to remove the last one:</p>
<pre><code>{exp:freeform:form form_name="{url_title}" form_id="{url_title}" template="{form_template}" notify="{form_notify}" return="{form_return}" <strong>required="{form_field search:required='y' backspace='1'}{field}|{/form_field}"</strong>}
&hellip;
{/exp:freeform:form}</code></pre>
<p>Next, we want to add a title, ordered list that will contain the form fields, and the submit button:</p>
<pre><code>{exp:freeform:form form_name="{url_title}" form_id="{url_title}" template="{form_template}" notify="{form_notify}" return="{form_return}" required="{form_field search:required='y' backspace='1'}{field}|{/form_field}"}
	&lt;h1>{title}&lt;/h1>
	&lt;ol class="forms">
		&hellip;
		&lt;li class="buttons">&lt;input type="submit" name="submit" value="submit" />&lt;/li>
	&lt;/ol>
{/exp:freeform:form}</code></pre>
<p>Now here is where the code gets interesting. Just like we did with the required parameter, we want to loop through each row in the FF Matrix and display a list item for each one:</p>
<pre><code>{form_field}
	&lt;li>
	&hellip;
	&lt;/li>
{/form_field}</code></pre>
<p>First, let&rsquo;s display the label, if there is one, and denote if the field is required or not:</p>
<pre><code>{if "{label}"}
	&lt;label for="{field}">{if "{required}" == "y"}&lt;em class="required">*&lt;/em>{/if}{label}&lt;/label>
{/if}</code></pre>
<p>The rest of the code is a big conditional statement which depends upon the Field Types that you specified in the FF Matrix. Let&rsquo;s first take a look at the <strong>Text Input</strong>, <strong>Textarea</strong>, and <strong>Checkbox</strong> types since they are pretty straightforward:</p>
<pre><code>{if "{type}" == "Text Input"}
	&lt;input type="text" name="{field}" id="{field}" />
{if:elseif "{type}" == "Textarea"}
	&lt;textarea name="{field}" id="{field}">&lt;/textarea>
{if:elseif "{type}" == "Checkbox"}
	&lt;input type="checkbox" class="checkbox" name="{field}" id="{field}" />
&hellip;
{/if}</code></pre>
<p>So we are just checking the type column in the FF Matrix, and then displaying the rest of the data from the row in the appropriate form field.</p>
<p>Next, let&rsquo;s walk through what happens if you select the <strong>Select</strong> or <strong>Multi-select</strong> types:</p>
<pre><code>{if:elseif "{type}" == "Select" || "{type}" == "Multi-select" &#038;&#038; "{options}"}
	&lt;select name="{field}{if "{type}" == "Multi-select"}[]{/if}" id="{field}"{if "{type}" == "Multi-select"} multiple="multiple" size="4"{/if}>
		&lt;?php $items = explode("|", '{options}'); ?>
		&lt;?php foreach ($items as $item) { ?>
			&lt;option value="&lt;?php echo $item; ?>">&lt;?php echo $item; ?>&lt;/option>
		&lt;?php } ?>
	&lt;/select>
&hellip;
{/if}</code></pre>
<p>So first, we are displaying the <strong>select element</strong>, and if it is a <strong>Multi-select</strong>, we are adding <strong>[]</strong> to the name attribute, and adding the <strong>multiple</strong> and <strong>size</strong> attributes.</p>
<p>Next, we want to take the string of <strong>options</strong> that are separated by the | character, and create an array out of the string using the <a href="http://php.net/manual/en/function.explode.php">explode function</a>.</p>
<p>Then, we loop through the array, and display the options for each one.</p>
<p>Finally, we do virtually the same thing for the <strong>Radio Group</strong> and <strong>Checkbox Group</strong> field types:</p>
<pre><code>{if:elseif "{type}" == "Radio Group" &#038;&#038; "{options}"}
	&lt;ul class="group">
		&lt;?php $items = explode("|", '{options}'); $count = 1; ?>
		&lt;?php foreach ($items as $item) { ?>
			&lt;li>&lt;input type="radio" class="radio" name="{field}" id="{field}&lt;?php echo $count; ?>" value="&lt;?php echo $item; ?>" />
			&lt;label for="{field}&lt;?php echo $count; ?>">&lt;?php echo $item; ?>&lt;/label>&lt;/li>
			&lt;?php $count++; ?>
		&lt;?php } ?>
	&lt;/ul>
{if:elseif "{type}" == "Checkbox Group" &#038;&#038; "{options}"}
	&lt;ul class="group">
		&lt;?php $items = explode("|", '{options}'); $count = 1; ?>
		&lt;?php foreach ($items as $item) { ?>
			&lt;li>&lt;input type="checkbox" class="checkbox" name="{field}[]" id="{field}&lt;?php echo $count; ?>" value="&lt;?php echo $item; ?>" />
			&lt;label for="{field}&lt;?php echo $count; ?>">&lt;?php echo $item; ?>&lt;/label>&lt;/li>
			&lt;?php $count++; ?>
		&lt;?php } ?>
	&lt;/ul>
{/if}</code></pre>
<p>So that&rsquo;s it really. Here is the full template:</p>
<pre><code>{exp:weblog:entries weblog="forms" limit="1" disable="categories|category_fields|member_data|pagination|trackbacks"}

	{exp:freeform:form form_name="{url_title}" form_id="{url_title}" template="{form_template}" notify="{form_notify}" return="{form_return}" required="{form_field search:required='y' backspace='1'}{field}|{/form_field}"}

		&lt;h1>{title}&lt;/h1>
		&lt;ol class="forms">
			{form_field}
				&lt;li>
					{if "{label}"}
						&lt;label for="{field}">{if "{required}" == "y"}&lt;em class="required">*&lt;/em>{/if}{label}&lt;/label>
					{/if}
					{if "{type}" == "Text Input"}
						&lt;input type="text" name="{field}" id="{field}" />
					{if:elseif "{type}" == "Textarea"}
						&lt;textarea name="{field}" id="{field}">&lt;/textarea>
					{if:elseif "{type}" == "Checkbox"}
						&lt;input type="checkbox" class="checkbox" name="{field}" id="{field}" />
					{if:elseif "{type}" == "Select" || "{type}" == "Multi-select" &#038;&#038; "{options}"}
						&lt;select name="{field}{if "{type}" == "Multi-select"}[]{/if}" id="{field}"{if "{type}" == "Multi-select"} multiple="multiple" size="4"{/if}>
							&lt;?php $items = explode("|", '{options}'); ?>
							&lt;?php foreach ($items as $item) { ?>
								&lt;option value="&lt;?php echo $item; ?>">&lt;?php echo $item; ?>&lt;/option>
							&lt;?php } ?>
						&lt;/select>
					{if:elseif "{type}" == "Radio Group" &#038;&#038; "{options}"}
						&lt;ul class="group">
							&lt;?php $items = explode("|", '{options}'); $count = 1; ?>
							&lt;?php foreach ($items as $item) { ?>
								&lt;li>&lt;input type="radio" class="radio" name="{field}" id="{field}&lt;?php echo $count; ?>" value="&lt;?php echo $item; ?>" />
								&lt;label for="{field}&lt;?php echo $count; ?>">&lt;?php echo $item; ?>&lt;/label>&lt;/li>
								&lt;?php $count++; ?>
							&lt;?php } ?>
						&lt;/ul>
					{if:elseif "{type}" == "Checkbox Group" &#038;&#038; "{options}"}
						&lt;ul class="group">
							&lt;?php $items = explode("|", '{options}'); $count = 1; ?>
							&lt;?php foreach ($items as $item) { ?>
								&lt;li>&lt;input type="checkbox" class="checkbox" name="{field}[]" id="{field}&lt;?php echo $count; ?>" value="&lt;?php echo $item; ?>" />
								&lt;label for="{field}&lt;?php echo $count; ?>">&lt;?php echo $item; ?>&lt;/label>&lt;/li>
								&lt;?php $count++; ?>
							&lt;?php } ?>
						&lt;/ul>
					{/if}
				&lt;/li>
			{/form_field}
			&lt;li class="buttons">&lt;input type="submit" name="submit" value="submit" />&lt;/li>
		&lt;/ol>
	{/exp:freeform:form}
{/exp:weblog:entries}</code></pre>
<h2>Conclusion</h2>
<p>This is not meant to be an all-inclusive form builder, as you can see there are <a href="http://www.solspace.com/docs/detail/freeform_form/#parameters">many other parameters for the Freeform module</a>. But, this was meant to show a creative use of ExpressionEngine and EE add-ons to add functionality that is not directly built into the CMS.</p>
<p>So go forth and create.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/freeform-fieldframe-expressionengine-form-builder/feed/</wfw:commentRss>
		<slash:comments>54</slash:comments>
		</item>
		<item>
		<title>Reversed Ordered List with jQuery</title>
		<link>http://trevordavis.net/blog/tutorial/reversed-ordered-list-jquery/</link>
		<comments>http://trevordavis.net/blog/tutorial/reversed-ordered-list-jquery/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 05:01:17 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=2191</guid>
		<description><![CDATA[At work this past week, a client requested something that I wasn&#8217;t sure how to achieve: a reversed ordered list. So basically, they wanted to have a top 10 list, with the first item being numbered 10 and the last 1.

If you want to skip ahead to the demo, go ahead.
View Demo
Now sure, I could [...]]]></description>
			<content:encoded><![CDATA[<p>At work this past week, a client requested something that I wasn&rsquo;t sure how to achieve: a reversed ordered list. So basically, they wanted to have a top 10 list, with the first item being numbered 10 and the last 1.</p>
<p><span id="more-2191"></span></p>
<p>If you want to <a href="http://trevordavis.net/play/reversed-ordered-list-with-jquery/">skip ahead to the demo</a>, go ahead.</p>
<p><a href="http://trevordavis.net/play/reversed-ordered-list-with-jquery/" class="more-link">View Demo</a></p>
<p>Now sure, I could have just written the numbers in as text, but it&rsquo;s a list, and it&rsquo;s ordered! Here is an example of what the client wanted:</p>
<p>10. Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
9. Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
8. Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
&hellip;<br />
1. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>After some digging around, I found out that you can add the <strong>value attribute</strong> to each list item to specify the number to display. So basically, I just needed to code my list like this:</p>
<pre><code>&lt;ol>
	&lt;li value="10">Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/li>
	&lt;li value="9">Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/li>
	&lt;li value="8">Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/li>
	&hellip;
	&lt;li value="1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/li>
&lt;/ol></code></pre>
<p>Pretty straightforward, but also pretty ugly. So what happens when the client decides they want to insert another bullet in the middle of the list? Yep, that&rsquo;s right, they would have to adjust the numbering for the rest of the list.</p>
<p>Pretty crappy, so let&rsquo;s use the powerfulness of jQuery to make this a little better.</p>
<h2>The Markup</h2>
<p>So just like before, we just want to create an ordered list, but this time, we will leave off the value attribute. We are also going to add a class to the ordered list that we will use as a hook to add in the jQuery functionality:</p>
<pre><code>&lt;ol class="reversed">
	&lt;li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/li>
	&lt;li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/li>
	&lt;li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/li>
	&hellip;
	&lt;li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/li>
&lt;/ol></code></pre>
<h2>The jQuery</h2>
<p>Mapping out the code a bit: we want to select each element with a class of reversed, and count the total number of children list items. Then, we want to loop through the children, and update the value attribute to be the value of the total number of children minus a counter variable that we started at zero and increment each time through the loop.</p>
<p>That seems relatively straightforward, so I&rsquo;ll just show the code that I wrote:</p>
<pre><code>$(document).ready(function() {
	$('.reversed').each(function() {
		var $children = $(this).children('li');
		var totalChildren = $children.length;
		var start = 0;
		$children.each(function() {
			$(this).val(totalChildren - start);
			start++;
		});
	});
});</code></pre>
<p><a href="http://trevordavis.net/play/reversed-ordered-list-with-jquery/" class="more-link">View Demo</a></p>
<p>It looks like with HTML 5, we get a <a href="http://blog.whatwg.org/reverse-ordered-lists">reversed attribute</a> that accomplishes the same thing, but until it&rsquo;s fully supported, this quick &amp; easy solution seems to work.</p>
<h2>On a Personal Note</h2>
<p>I have been severely neglecting my blog, but for good reason. I have been teaching some intro to web development courses at <a href="http://www.cdiabu.com/">CDIABU</a> in Georgetown. Also, I will be starting a new job on December 1st. I will be joining the amazing team at <a href="http://www.viget.com/">Viget Labs</a> as their new front-end developer.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/reversed-ordered-list-jquery/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>ExpressionEngine: Embed an Embed within Itself?</title>
		<link>http://trevordavis.net/blog/tutorial/expressionengine-embed-an-embed-within-itself/</link>
		<comments>http://trevordavis.net/blog/tutorial/expressionengine-embed-an-embed-within-itself/#comments</comments>
		<pubDate>Sat, 17 Oct 2009 17:00:25 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=2143</guid>
		<description><![CDATA[At work this week, there was discussion on how to accomplish something in ExpressionEngine. We wanted to pull in entries that were in one category, but if there were no entries, then pull in from other categories and display that instead. We were kind of stumped as to how to do that.

I&#8217;m not sure if [...]]]></description>
			<content:encoded><![CDATA[<p>At work this week, there was discussion on how to accomplish something in ExpressionEngine. We wanted to pull in entries that were in one category, but if there were no entries, then pull in from other categories and display that instead. We were kind of stumped as to how to do that.</p>
<p><span id="more-2143"></span></p>
<p>I&rsquo;m not sure if we were missing some easy way to do that, but we couldn&rsquo;t think of a nice way to accomplish it.</p>
<h2>Let&rsquo;s Backup</h2>
<p>I guess it will be helpful to give you some more context. We had created a Channel (our term for Weblog) for <strong>events</strong>. You could categorize the events, and they would publish in different places.</p>
<p>In this instance, the homepage, we wanted to pull an event from one category, but if there were none, then just display an event from another category.</p>
<h2>The Initial Code</h2>
<p>This code was separated out in an embed so that we could use it in various places on the site:</p>
<pre><code>{assign_variable:channel_name="{embed:channel}"}
{assign_variable:category_id="{embed:category}"}

{exp:weblog:entries weblog="{channel_name}" category="{category_id}" show_future_entries="yes" show_expired="no" limit="1" disable=â€œcategory_fields|custom_fields|member_data|pagination|trackbacksâ€}

	&lt;h2>{title}&lt;/h2>
	{if events_feature_image}
		&lt;p class="rightSide">&lt;a href="{url_title_path="{embed:template_path}"}">&lt;img src="{events_feature_image}" alt="" />&lt;/a>&lt;/p>
	{/if}
	{if events_summary}
		{events_summary}
	{/if}

	&lt;p>&lt;a href="{url_title_path="{embed:template_path}"}" class="more">Read more &raquo;&lt;/a>&lt;/p>
{/exp:weblog:entries}</code></pre>
<p>The code doesn&rsquo;t really need to be explained; it&rsquo;s not the important part of this post. So on the homepage, we had code that looked like this to pull in the event:</p>
<pre><code>{embed="site/.events" channel="events" category="7" template_path="news-events/events"}</code></pre>
<p>Now, what we really wanted to be able to do was to modify the <strong>exp:weblog:entries</strong> code to pull from a different category if there were no results. Something like this:</p>
<pre><code>{exp:weblog:entries weblog="{channel_name}" category="{category_id}" show_future_entries="yes" show_expired="no" limit="1" disable=â€œcategory_fields|custom_fields|member_data|pagination|trackbacksâ€}
&hellip;
	{if no_results}
		Code  to pull from a different category
	{/if}
&hellip;
{/exp:weblog:entries}</code></pre>
<p>But the problem was, there really was no code that we could put in there that would pull from another category since you can&rsquo;t nest <strong>exp:weblog:entries</strong> tags. So that&rsquo;s when I remembered that you could stick an embed file in there that could have the <strong>exp:weblog:entries</strong> tag inside of it.</p>
<p>Then we realized that the code we wanted to write would be exactly like the code in the embed file we were already working with.</p>
<p>So we did a little investigation and found out that <a href="http://expressionengine.com/docs/templates/embedding_templates.html">according to the documentation (see notes section)</a>, you cannot embed an embed within itself.</p>
<p>That makes sense, because you could create an infinite loop. But what if we knew that it would not return an infinite loop?</p>
<h2>Modified Code</h2>
<p>So we determined that what we could do is not pass in the category on the embed statement, and that would pull back any events.</p>
<pre><code>{exp:weblog:entries weblog="{channel_name}" category="{category_id}" show_future_entries="yes" show_expired="no" limit="1" disable=â€œcategory_fields|custom_fields|member_data|pagination|trackbacksâ€}
&hellip;
	{if no_results}
		{embed="site/.events" channel="events" template_path="news-events/events"}
	{/if}
&hellip;
{/exp:weblog:entries}</code></pre>
<p>See how there is no category parameter this time? Here is the full modified code:</p>
<pre><code>{assign_variable:channel_name="{embed:channel}"}
{assign_variable:category_id="{embed:category}"}

{exp:weblog:entries weblog="{channel_name}" category="{category_id}" show_future_entries="yes" show_expired="no" limit="1" disable=â€œcategory_fields|custom_fields|member_data|pagination|trackbacksâ€}

	&lt;h2>{title}&lt;/h2>
	{if events_feature_image}
		&lt;p class="rightSide">&lt;a href="{url_title_path="{embed:template_path}"}">&lt;img src="{events_feature_image}" alt="" />&lt;/a>&lt;/p>
	{/if}
	{if events_summary}
		{events_summary}
	{/if}

	&lt;p>&lt;a href="{url_title_path="{embed:template_path}"}" class="more">Read more &raquo;&lt;/a>&lt;/p>

	<strong>{if no_results}
		{embed="site/.events" channel="events" template_path="news-events/events"}
	{/if}</strong>
{/exp:weblog:entries}</code></pre>
<p><strong>And that worked!</strong></p>
<h2>Houston, we still have a problem&hellip;</h2>
<p>But, we then realized that the same problem would occur if there were no future events in any categories. So, we still needed to go back and solve that problem by similarly passing the value for the <strong>show_expired</strong> parameter in the embed statement as well. I left that to my colleague, so I didn&rsquo;t test this code, but this is my guess of how to solve that problem:</p>
<pre><code>{assign_variable:channel_name="{embed:channel}"}
{assign_variable:category_id="{embed:category}"}
<strong>{assign_variable:show_expired="{embed:show_expired}"}</strong>

{exp:weblog:entries weblog="{channel_name}" category="{category_id}" show_future_entries="yes" <strong>show_expired="{show_expired}"</strong> limit="1" disable=â€œcategory_fields|custom_fields|member_data|pagination|trackbacksâ€}

	&lt;h2>{title}&lt;/h2>
	{if events_feature_image}
		&lt;p class="rightSide">&lt;a href="{url_title_path="{embed:template_path}"}">&lt;img src="{events_feature_image}" alt="" />&lt;/a>&lt;/p>
	{/if}
	{if events_summary}
		{events_summary}
	{/if}

	&lt;p>&lt;a href="{url_title_path="{embed:template_path}"}" class="more">Read more &raquo;&lt;/a>&lt;/p>

	{if no_results}
		{embed="site/.events" channel="events" <strong>show_expired="yes"</strong> template_path="news-events/events"}
	{/if}
{/exp:weblog:entries}</code></pre>
<h2>Conclusion</h2>
<p>Was there some really easy way to do this that we completely blanked on? It seemed a little <em>hacky</em>, but the solution worked.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/expressionengine-embed-an-embed-within-itself/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Simple jQuery Text Resizer</title>
		<link>http://trevordavis.net/blog/tutorial/simple-jquery-text-resizer/</link>
		<comments>http://trevordavis.net/blog/tutorial/simple-jquery-text-resizer/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 02:25:43 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=2072</guid>
		<description><![CDATA[I have done JavaScript text resizers a couple of different ways before, but I think I found my favorite way on a recent project. In previous projects, I have messed around with determining the current font size and adjusting it appropriately. But, in my opinion, simplifying things has made it a much better implementation.

If you [...]]]></description>
			<content:encoded><![CDATA[<p>I have done JavaScript text resizers a couple of different ways before, but I think I found my favorite way on a recent project. In previous projects, I have messed around with determining the current font size and adjusting it appropriately. But, in my opinion, simplifying things has made it a much better implementation.</p>
<p><span id="more-2072"></span></p>
<p>If you want to skip right to the <a href="http://trevordavis.net/play/jquery-text-resizer/">demo</a>, feel free.</p>
<p><a href="http://trevordavis.net/play/jquery-text-resizer/" class="more-link">View Demo</a></p>
<h2>Disclaimer</h2>
<p>Let me first say that I have started to size text in pixels and <a href="http://danielmall.com/archives/2007/04/20/soft_serve.php">soft serving</a> EMs to IE6. There are tons of different font sizing techniques you can use, but this is what is working for me. So use whatever technique you please, and adjust as needed.</p>
<p>Another thing: <strong>I hate text resizers</strong>. In my opinion, there is no reason to duplicate browser functionality. I feel the same about back and print links, but sometimes the functionality is requested, so I have to build it.</p>
<h2>Concept</h2>
<p>The idea is very simple: you click on the text size you want, and a class is added to the body to indicate which size the user has selected. Then, we take advantage of that body class when we are writing our CSS to size the different elements appropriately.</p>
<h2>Code</h2>
<p>Let&rsquo;s first start as we always should, by creating the markup:</p>
<pre><code>&lt;ul class="resizer">
	&lt;li class="small">&lt;a href="#">A&lt;/a>&lt;/li>
	&lt;li class="medium">&lt;a href="#">A&lt;/a>&lt;/li>
	&lt;li class="large">&lt;a href="#">A&lt;/a>&lt;/li>
&lt;/ul></code></pre>
<h3>jQuery</h3>
<p>The markup was simple enough, so let&rsquo;s get started on the jQuery. First, we want to execute our code when the document is loaded, and then add an event when one of the resizer links are clicked:</p>
<pre><code>$(document).ready(function() {
	$('.resizer a').click(function() {

	});
});</code></pre>
<p>Next, we want to get the class of the parent of the link that has been clicked, remove any of the resizer classes from the body, and add the new one:</p>
<pre><code>$(document).ready(function() {
	$('.resizer a').click(function() {
		var textSize = $(this).parent().attr('class');
		$('body').removeClass('small medium large').addClass(textSize);
	});
});</code></pre>
<p>We also don&rsquo;t want to regular action of the link to be followed, so we need to <strong>return false</strong>:</p>
<pre><code>$(document).ready(function() {
	$('.resizer a').click(function() {
		var textSize = $(this).parent().attr('class');
		$('body').removeClass('small medium large').addClass(textSize);
		return false;
	});
});</code></pre>
<p>I also think it is important to remember what text size a user has selected while browsing the site, so we will take advantage of the <a href="http://plugins.jquery.com/project/cookie">jQuery Cookie plugin</a> to help us with that. We will set a cookie that denotes which size the user has selected:</p>
<pre><code>$(document).ready(function() {
	$('.resizer a').click(function() {
		var textSize = $(this).parent().attr('class');
		$('body').removeClass('small medium large').addClass(textSize);
		$.cookie('TEXT_SIZE',textSize, { path: '/', expires: 10000 });
		return false;
	});
});</code></pre>
<p>Finally, we just need to add a check to the beginning of the script, so that if that cookie is set, we add that size as a class to the body:</p>
<pre><code>$(document).ready(function() {
	if($.cookie('TEXT_SIZE')) {
		$('body').addClass($.cookie('TEXT_SIZE'));
	}
	$('.resizer a').click(function() {
		var textSize = $(this).parent().attr('class');
		$('body').removeClass('small medium large').addClass(textSize);
		$.cookie('TEXT_SIZE',textSize, { path: '/', expires: 10000 });
		return false;
	});
});</code></pre>
<h3>CSS</h3>
<p> Now is where we get to the really powerful part of doing the text resizing like this: the CSS. We can start by simply stating our text size when it is in the small/default state:</p>
<pre><code>body { font: 12px/18px Arial, sans-serif; }</code></pre>
<p>Then, we just need to make a simple adjustment for the medium and large sizes:</p>
<pre><code>.medium { font-size: 16px; line-height: 22px; }
.large { font-size: 20px; line-height: 26px; }</code></pre>
<p>So you can just carry through this idea for the rest of the elements that have been assigned a font size:</p>
<pre><code>h1 { font-size: 30px; line-height: 36px; }
.medium h1 { font-size: 34px; line-height: 40px; }
.large h1 { font-size: 38px; line-height: 44px; }
h2 { font-size: 24px; line-height: 30px; }
.medium h2 { font-size: 28px; line-height: 34px; }
.large h2 { font-size: 32px; line-height: 38px; }
h3 { font-size: 18px; line-height: 24px; }
.medium h3 { font-size: 22px; line-height: 28px; }
.large h3 { font-size: 26px; line-height: 32px; }</code></pre>
<p><a href="http://trevordavis.net/play/jquery-text-resizer/" class="more-link">View Demo</a></p>
<p>The idea is very simple, and it really separates the presentation and behavioral layers. So what do you think? Do you have another technique that you like?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/simple-jquery-text-resizer/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Create a Newsletter with ExpressionEngine &amp; FieldFrame</title>
		<link>http://trevordavis.net/blog/tutorial/create-newsletter-expressionengine-fieldframe/</link>
		<comments>http://trevordavis.net/blog/tutorial/create-newsletter-expressionengine-fieldframe/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 04:36:36 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=2049</guid>
		<description><![CDATA[I guess it is time to come back from my little hiatus to actually write a blog post. I recently moved, so I have been busy with getting settled and working on freelance projects as well. If you follow me on Twitter, you may have noticed that I have recently become obsessed with ExpressionEngine. I [...]]]></description>
			<content:encoded><![CDATA[<p>I guess it is time to come back from my little hiatus to actually write a blog post. I recently moved, so I have been busy with getting settled and working on freelance projects as well. If you <a href="http://twitter.com/davist11">follow me on Twitter</a>, you may have noticed that I have recently become obsessed with ExpressionEngine. I completed a <a href="http://trevordavis.net/work/ecfc/">project</a> at work using it, and I realized that I could have done something much more efficiently.</p>
<p><span id="more-2049"></span></p>
<p><a href="http://ee.trevordavis.net/newsletter/" class="more-link">View Demo</a></p>
<p>I had to create an &ldquo;online newsletter&rdquo; that had issues that were made up of multiple articles. I ended up creating two separate weblogs: one for each issue, and one for individual articles. In the issues weblog, there was a <a href="http://brandon-kelly.com/playa">Playa</a> custom field which could be used to pick the individual articles to be published in that issue. But, another one of Brandon Kelly&rsquo;s fabulous extensions, <a href="http://brandon-kelly.com/fieldframe">FieldFrame</a>, seems to be a much better choice for creating this functionality.</p>
<p>So, download, install, &amp; enable the <a href="http://brandon-kelly.com/fieldframe">FieldFrame Extension</a>, and let&rsquo;s be on our way.</p>
<h2>Creating the Custom Field Group</h2>
<p>First, let&rsquo;s create a field group named <strong>Newsletter</strong>. Now, we just need to create one custom field with the field name of <strong>newsletter_articles</strong>. Select <strong>FF Matrix</strong> as the field type.</p>
<p>We want to have two cells in the FF Matrix: <strong>articles_title</strong> &#038; <strong>articles_body</strong>. The cell types should be text and textarea, respectively. Then, adjust the sizes as you see fit.</p>
<p><img src="http://trevordavis.net/wp-content/uploads/2009/08/newsletter-ff.png" alt="FF Matrix Configuration" width="570" height="282" class="frame pullLeft" /></p>
<h2>Creating the Weblog</h2>
<p>Now that we have the custom field group setup, we need to create a new weblog called <strong>newsletter</strong> and make sure to assign our <strong>Newsletter field group</strong> to it. Now that the newsletter weblog is created, we can start adding newsletters.</p>
<p><img src="http://trevordavis.net/wp-content/uploads/2009/08/newletter-entry.png" alt="Newsletter Entry Form" width="570" height="304" class="frame pullLeft" /></p>
<p>First, fill in the main title field, and then add in one or more articles. Now, let&rsquo;s get onto coding the output template.</p>
<h2>Creating the Template</h2>
<p>Let&rsquo;s start by creating a new template group called <strong>newsletter</strong>. We have two different pages that we want to create: the page listing all of the newsletter entries, and the individual newsletter entry displaying all of the articles. But, we can do this with only one template.</p>
<p>So, open up the index template in the newsletter template group, and we will start by setting up the structure of the template:</p>
<pre><code>{assign_variable:weblog="newsletter"}
{embed="newsletter/.header" title="{if segment_2}
	{!--Display individual newsletter entry title here--}
{if:else}
	Newsletters
{/if}
"}

{if segment_2}
	{!--Display full individual newsletter entry with 1 or more articles--}
{if:else}
	{!--Display list of newsletters entered--}
{/if}

{embed="newsletter/.footer"}</code></pre>
<p>We start by creating a variable to store the name of our weblog. Then, I created a simple header and footer to store some of the HTML that frames the page. I am passing in the title value in an embed variable to the header and displaying that in the browser title.</p>
<p>If the segment_2 value is not null, we know that we are on an individual newsletter page, so we will display that title. If the segment_2 value is null, then we are on the main newsletter listing page, so we just display Newsletters.</p>
<p>We are using the same conditional again for the content on the page. We either show the individual newsletter entry with the articles, or we show the list of newsletter entered. So let&rsquo;s build out the code a little more. First, let&rsquo;s finish displaying the title:</p>
<pre><code>{embed="newsletter/.header" title="{if segment_2}
	{exp:weblog:entries weblog="{weblog}" limit="1" disable="categories|category_fields|custom_fields|member_data|pagination|trackbacks"}
		{title} : {entry_date format="%F %j, %Y"}
	{/exp:weblog:entries}
{if:else}
	Newsletters
{/if}
"}</code></pre>
<p>Pretty simple stuff here, just displaying the title and entry date of the newsletter entry. Next, let&rsquo;s tackle displaying the single newsletter entry view:</p>
<pre><code>{if segment_2}
	{exp:weblog:entries weblog="{weblog}" limit="1" disable="categories|category_fields|custom_fields|member_data|pagination|trackbacks"}
		&lt;h1>{title}: {entry_date format="%F %j, %Y"}&lt;/h1>

		{newsletter_articles}
			&lt;div class="entry">
				&lt;h2>{articles_title}&lt;/h2>
				{articles_body}
			&lt;/div>
		{/newsletter_articles}
	{/exp:weblog:entries}
	&lt;p>&lt;a href="{path="newsletter"}">&laquo; Back to Newsletters&lt;/a>&lt;/p></code></pre>
<p>The beginning should look pretty normal: just using the standard exp:weblog:entries tag to pull in the individual entry. We first display the title and entry date. Then, the next part is where we are taking advantage of the <a href="http://brandon-kelly.com/fieldframe/docs/ff-matrix">FieldFrame Matrix</a>. We are basically just looping through all of the <strong>newsletter_articles</strong> and displaying them in divs.</p>
<p>Finally, let&rsquo;s finish up by displaying the list of newsletter entries:</p>
<pre><code>{if:else}
	{exp:weblog:entries weblog="{weblog}" disable="categories|category_fields|custom_fields|member_data|pagination|trackbacks"}
		{if count == 1}
			&lt;ul>
		{/if}

			&lt;li>&lt;a href="{url_title_path="newsletter"}">{title}: {entry_date format="%F %j, %Y"}&lt;/a>&lt;/li>
		{if count == total_results}
			&lt;/ul>
		{/if}
	{/exp:weblog:entries}
{/if}</code></pre>
<p>Simple stuff again: just looping through all newsletter entries and displaying them in a list. The two conditional statements are so you don&rsquo;t end up with any empty unordered lists when there are no entries.</p>
<p><a href="http://ee.trevordavis.net/newsletter/" class="more-link">View Demo</a></p>
<p>I wish I would have realized this would have been a more efficient way to build a newsletter in EE for the project; but, this is why always learning is so important.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/create-newsletter-expressionengine-fieldframe/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>jQuery Inline Form Labels</title>
		<link>http://trevordavis.net/blog/tutorial/jquery-inline-form-labels/</link>
		<comments>http://trevordavis.net/blog/tutorial/jquery-inline-form-labels/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 05:25:27 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1938</guid>
		<description><![CDATA[I&#8217;ve been seeing the trend of applying inline labels on form elements more and more these days. So I definitely needed to come up with a solid solution that would help me easily apply this effect.

Maybe I need to explain a little better what I am referring to. Instead of using a label that is [...]]]></description>
			<content:encoded><![CDATA[<p>I&rsquo;ve been seeing the trend of applying inline labels on form elements more and more these days. So I definitely needed to come up with a solid solution that would help me easily apply this effect.</p>
<p><span id="more-1938"></span></p>
<p><a href="http://trevordavis.net/play/jquery-inline-form-labels/"><img src="http://trevordavis.net/wp-content/uploads/2009/06/jquery-inline-labels.png" alt="jQuery Inline Form Labels" width="280" height="169" class="leftSide pullLeft" /></a>Maybe I need to explain a little better what I am referring to. Instead of using a label that is next to or above the input element, the label is actually within the input. Then, when the input is focused, the label goes away and you can enter your value into it. Finally, when the input is no longer focused, if there is no value entered, the inline label is then added back in.</p>
<p><a href="http://trevordavis.net/play/jquery-inline-form-labels/" class="more-link">See Demo</a></p>
<h2>My Solution</h2>
<p>The title attribute.</p>
<p>It&rsquo;s so simple, but perfect. A great benefit of using the title attribute, is that when you hover over the input, you get a little tooltip displaying the inline label. So all I need to do is add a title attribute with the text that we want to have show up as the inline label. Then, we just use a little jQuery to make it all happen.</p>
<h3>The jQuery</h3>
<p>First, we want to select each input that has a title attribute, once the document is loaded:</p>
<pre><code>$(document).ready(function() {
	$('input[title]').each(function() {
	&hellip;
	});
});</code></pre>
<p>Next, if the value of the input element is empty, we want to take the title attribute and add it as the value of the input.</p>
<pre><code>$(document).ready(function() {
	$('input[title]').each(function() {
		<strong>if($(this).val() === '') {
			$(this).val($(this).attr('title'));
		}</strong>
	});
});</code></pre>
<p>After that, we want to setup a function that will fire once the input is focused. When it is focused, if the value is equal to the title attribute, we want to set the value to nothing and add a class of focused:</p>
<pre><code>$(document).ready(function() {
	$('input[title]').each(function() {
		if($(this).val() === '') {
			$(this).val($(this).attr('title'));
		}

		<strong>$(this).focus(function() {
			if($(this).val() === $(this).attr('title')) {
				$(this).val('').addClass('focused');
			}
		});</strong>
	});
});</code></pre>
<p>The reason why we add the class of focused is so that we can change the text color, border or anything to make it noticeable that the input is being focused. You can see this effect in the <a href="http://trevordavis.net/play/jquery-inline-form-labels/">demo</a>.</p>
<p>Finally, we want to add a function that will fire when the input loses focus. When it does, if the input value is empty, we want to set the value back to the title attribute and remove the class of focused:</p>
<pre><code>$(document).ready(function() {
	$('input[title]').each(function() {
		if($(this).val() === '') {
			$(this).val($(this).attr('title'));
		}

		$(this).focus(function() {
			if($(this).val() === $(this).attr('title')) {
				$(this).val('').addClass('focused');
			}
		});

		<strong>$(this).blur(function() {
			if($(this).val() === '') {
				$(this).val($(this).attr('title')).removeClass('focused');
			}
		});</strong>
	});
});</code></pre>
<p><a href="http://trevordavis.net/play/jquery-inline-form-labels/" class="more-link">See Demo</a></p>
<p>And that&rsquo;s it. It&rsquo;s just a little bit of code, but it can go a long way. So take it and build on it.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/jquery-inline-form-labels/feed/</wfw:commentRss>
		<slash:comments>42</slash:comments>
		</item>
		<item>
		<title>Dynamically Set a Body Id in PHP</title>
		<link>http://trevordavis.net/blog/tutorial/dynamically-set-a-body-id/</link>
		<comments>http://trevordavis.net/blog/tutorial/dynamically-set-a-body-id/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 05:38:26 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1736</guid>
		<description><![CDATA[I have already written a couple of articles about body ids: 
Set a Body Id Using PHP and Setting Body Ids in Expression Engine, but in a recent project, I was looking for a more dynamic way to do it in PHP and WordPress.

I don&#8217;t think it&#8217;s necessary to discuss the benefits of body ids [...]]]></description>
			<content:encoded><![CDATA[<p>I have already written a couple of articles about body ids: <a href="http://trevordavis.net/blog/tutorial/set-a-body-id/"><br />
Set a Body Id Using PHP</a> and <a href="http://trevordavis.net/blog/tutorial/setting-body-ids-in-expression-engine/">Setting Body Ids in Expression Engine</a>, but in a recent project, I was looking for a more dynamic way to do it in PHP and WordPress.</p>
<p><span id="more-1736"></span></p>
<p>I don&rsquo;t think it&rsquo;s necessary to discuss the benefits of body ids because I have already discussed them in the other posts. So if you still aren&rsquo;t using body ids/classes, go read the articles, and start using them.</p>
<h2>The Plan</h2>
<p>This seems so straightforward that I&rsquo;m not sure why I didn&rsquo;t start with this method. So basically, I look at the URI, and if it is equal to <strong>/</strong> then I give it a <strong>body id of home</strong>. Otherwise, I grab the <strong>first &ldquo;folder&rdquo; and set that as the body id</strong>.</p>
<h3>Example</h3>
<p>Let&rsquo;s say that the URI is: <strong>/about/team/leadership/</strong>. The body id would be <strong>about</strong>. Ok, the seems easy, let&rsquo;s get to the code.</p>
<h2>The Code</h2>
<p>Here is our setBodyId function:</p>
<pre><code>function setBodyId() {
	$path = $_SERVER['REQUEST_URI'];

	if($path === '/') {
		$bodyId = 'home';
	} else {
		$bodyId = substr($path, 1, (strpos($path,'/',1)-1));
	}

	return $bodyId;
}</code></pre>
<p class="note"><em>If you are using this in WordPress, put this function in your theme function.php file.</em></p>
<p>Then, you want to call the function and assign it to a variable:</p>
<pre><code>$bodyId = setBodyId();</code></pre>
<p>Finally, if the $bodyId variable is not empty, add the id attribute on the body tag:</p>
<pre><code>&lt;body&lt;?php if(!empty($bodyId)) echo ' id="'.$bodyId.'"';?>></code></pre>
<h2>Conclusion</h2>
<p>It&rsquo;s so simple, yet powerful. This could also easily be recoded in other programming languages. What do you think? Any ideas for improvement?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/dynamically-set-a-body-id/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>WordPress &amp; jQuery Contact Form without a Plugin</title>
		<link>http://trevordavis.net/blog/tutorial/wordpress-jquery-contact-form-without-a-plugin/</link>
		<comments>http://trevordavis.net/blog/tutorial/wordpress-jquery-contact-form-without-a-plugin/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 06:07:39 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1647</guid>
		<description><![CDATA[There are lots of WordPress plugins for contact forms, but wouldn&#8217;t it be nice to have more control over the markup? In this tutorial, I am going to show how to use a custom page template to create a contact form in WordPress without a plugin.

Some people may want to skip the post and get [...]]]></description>
			<content:encoded><![CDATA[<p>There are <a href="http://wordpress.org/extend/plugins/search.php?q=contact">lots of WordPress plugins for contact forms</a>, but wouldn&rsquo;t it be nice to have more control over the markup? In this tutorial, I am going to show how to use a custom page template to create a contact form in WordPress without a plugin.</p>
<p><span id="more-1647"></span></p>
<p>Some people may want to skip the post and get to the demo and source files:</p>
<p class="clearfix last"><a href="http://trevordavis.net/contact-form/" class="leftSide more-link">View Demo</a> <a href="http://trevordavis.net/wp-content/uploads/2009/02/contact-form.zip" class="leftSide more-link">Download Source Files</a></p>
<h2>So, why not use a plugin?</h2>
<p>Well, I think that a contact form is so simple that a WordPress plugin that doesn&rsquo;t provide exactly what I want is pretty lame. Plus, I don&rsquo;t need all those fancy interfaces for building the form; I just need the code.</p>
<h2>The Plan</h2>
<p>Our plan is to create a custom <a href="http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates">WordPress Page Template</a>, then create a page that uses that template. Finally, we will add in a little <strong>jQuery</strong> to improve the form. Let&rsquo;s write a little pseudo code to help determine how our page template will be structured.</p>
<h3>Pseudo Code</h3>
<pre><code>If form was submitted validate it
	If the form was submitted successfully
		Send email(s)
	Else
		Set variables to show errors

If the form was submitted successfully
	Show thank you message
Else
	Show form (with errors if there are any)</code></pre>
<h3>Creating the WordPress Page Template</h3>
<p>Alright, so first, we are going to start with some basic stuff: define the template name, include the header/sidebar/footer, and setup the basic structure of our pseudo code.</p>
<pre><code>&lt;?php
/*
Template Name: Contact Form
*/
?>

&lt;?php
//If the form is submitted
if(isset($_POST['submitted'])) {
	//If there is no error, send the email
	if(!isset($hasError)) {

	}
} ?>

&lt;?php get_header(); ?>

&lt;?php
//If the email was sent, show a thank you message
//Otherwise show form
if(isset($emailSent) &#038;&#038; $emailSent == true) {
?>

&lt;?php } else { ?>

&lt;?php } ?>

&lt;?php get_sidebar(); ?>

&lt;?php get_footer(); ?></code></pre>
<h3>The Form</h3>
<p>Next, let&rsquo;s code the actual form. I also want to provide the ability for the user to enter some text to go above the form, so we are going to use the regular loop:</p>
<pre><code>&lt;?php if(isset($emailSent) &#038;&#038; $emailSent == true) { ?>

	&lt;div class="thanks">
		&lt;h1>Thanks, &lt;?=$name;?>&lt;/h1>
		&lt;p>Your email was successfully sent. I will be in touch soon.&lt;/p>
	&lt;/div>

&lt;?php } else { ?>

	&lt;?php if (have_posts()) : ?>

		&lt;?php while (have_posts()) : the_post(); ?>
			&lt;h1>&lt;?php the_title(); ?>&lt;/h1>
			&lt;?php the_content(); ?>

			&lt;?php if(isset($hasError) || isset($captchaError)) { ?>
				&lt;p class="error">
					There was an error submitting the form.
				&lt;p>
			&lt;?php } ?>

			&lt;form action="&lt;?php the_permalink(); ?>" id="contactForm" method="post">

			&lt;/form>

		&lt;?php endwhile; ?>
	&lt;?php endif; ?>
&lt; } ?></code></pre>
<p>If the <strong>emailSent</strong> variable is set to true, we display the thank you message. Otherwise, we show the form. So we are outputting the title of the page, and any content that was entered. Then, we are checking to see if there was an error. Finally, we display the form:</p>
<pre><code>&lt;ol class="forms">
	&lt;li>
		&lt;label for="contactName">Name&lt;/label>
		&lt;input type="text" name="contactName" id="contactName" value="
		&lt;?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>"
		 class="requiredField" />
		&lt;?php if($nameError != '') { ?>
			&lt;span class="error">&lt;?=$nameError;?>&lt;/span>
		&lt;?php } ?>
	&lt;/li>

	&lt;li>
		&lt;label for="email">Email&lt;/label>
		&lt;input type="text" name="email" id="email" value="
		&lt;?php if(isset($_POST['email']))  echo $_POST['email'];?>"
		class="requiredField email" />
		&lt;?php if($emailError != '') { ?>
			&lt;span class="error">&lt;?=$emailError;?>&lt;/span>
		&lt;?php } ?>
	&lt;/li>

	&lt;li class="textarea">
		&lt;label for="commentsText">Comments&lt;/label>
		&lt;textarea name="comments" id="commentsText" rows="20" cols="30" class="requiredField">
		&lt;?php if(isset($_POST['comments'])) {
			if(function_exists('stripslashes')) {
				echo stripslashes($_POST['comments']);
			} else {
				echo $_POST['comments'];
			}
		 } ?>&lt;/textarea>
		&lt;?php if($commentError != '') { ?>
			&lt;span class="error">&lt;?=$commentError;?>&lt;/span>
		&lt;?php } ?>
	&lt;/li>
	&lt;li class="inline">
		&lt;input type="checkbox" name="sendCopy" id="sendCopy" value="true"
		&lt;?php if(isset($_POST['sendCopy']) &#038;&#038; $_POST['sendCopy'] == true)
			echo ' checked="checked"'; ?>
		/>
		&lt;label for="sendCopy">Send a copy of this email to yourself&lt;/label>
	&lt;/li>
	&lt;li class="screenReader">
		&lt;label for="checking" class="screenReader">If you want to submit this form, do not enter anything in this field&lt;/label>
		&lt;input type="text" name="checking" id="checking" class="screenReader" value="
		&lt;?php if(isset($_POST['checking']))  echo $_POST['checking'];?>"
		/>
	&lt;/li>
	&lt;li class="buttons">
		&lt;input type="hidden" name="submitted" id="submitted" value="true" />
		&lt;button type="submit">Email me &raquo;&lt;/button>
	&lt;/li>
&lt;/ol></code></pre>
<p class="note"><em>Note: Line wrapping added for readability.</em></p>
<p>Ok, wow, that may seem like a lot. So let&rsquo;s break down the name field to see what this code is actually doing:</p>
<pre><code>&lt;li>&lt;label for="contactName">Name&lt;/label>
	&lt;input type="text" name="contactName" id="contactName" value="&lt;?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField" />
	&lt;?php if($nameError != '') { ?>
		&lt;span class="error">&lt;?=$nameError;?>&lt;/span>
	&lt;?php } ?>
&lt;/li></code></pre>
<p>We are displaying each form field in a list item, displaying the label, input field, and then showing an error message if there is one. We are also displaying the value in the form field if it was already submitted.</p>
<p>So in essence, we are just doing that for each field of the form. You could easily go into the code to add more fields.</p>
<p>We are also using honeypot captcha to see if a bot was trying to submit the form:</p>
<pre><code>&lt;li class="screenReader">
	&lt;label for="checking" class="screenReader">If you want to submit this form, do not enter anything in this field&lt;/label>
	&lt;input type="text" name="checking" id="checking" class="screenReader" value="&lt;?php if(isset($_POST['checking']))  echo $_POST['checking'];?>" />
&lt;/li></code></pre>
<p>That list item is pushed off the page with CSS, and if there is a value in that field, we can assume that it is not a human trying to submit the form:</p>
<pre><code>.screenReader {
	left: -9999px;
	position: absolute;
	top: -9999px;
}</code></pre>
<h3>The Validation</h3>
<p>Next, we are going to have a conditional statement to determine if the form was submitted or not:</p>
<pre><code>&lt;?php
//If the form is submitted
if(isset($_POST['submitted'])) {

} ?></code></pre>
<p>Within that conditional, is where we are going to do all of our validation of the required fields. First, let&rsquo;s check to see if our honeypot captcha form field is filled in. If it is, then we will display an error and not check anymore of the form:</p>
<pre><code>//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
	$captchaError = true;
} else {

} </code></pre>
<p>So if the captcha field was left blank, we will continue to validate the required fields:</p>
<pre><code>//Check to make sure that the name field is not empty
if(trim($_POST['contactName']) === '') {
	$nameError = 'You forgot to enter your name.';
	$hasError = true;
} else {
	$name = trim($_POST['contactName']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '')  {
	$emailError = 'You forgot to enter your email address.';
	$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
	$emailError = 'You entered an invalid email address.';
	$hasError = true;
} else {
	$email = trim($_POST['email']);
}

//Check to make sure comments were entered
if(trim($_POST['comments']) === '') {
	$commentError = 'You forgot to enter your comments.';
	$hasError = true;
} else {
	if(function_exists('stripslashes')) {
		$comments = stripslashes(trim($_POST['comments']));
	} else {
		$comments = trim($_POST['comments']);
	}
}</code></pre>
<p>Again, that may seem like a little much, so let&rsquo;s just take a look at the validation on the name field:</p>
<pre><code>if(trim($_POST['contactName']) === '') {
	$nameError = 'You forgot to enter your name.';
	$hasError = true;
} else {
	$name = trim($_POST['contactName']);
}</code></pre>
<p>If the name field if empty, set a variable that will display the name error and set a flag saying that there was an error on the form. Otherwise, set a variable that will contain the name value from the form.</p>
<h3>Sending the Email</h3>
<p>Now, we want to send the email if there are no errors:</p>
<pre><code>//If there is no error, send the email
if(!isset($hasError)) {

	$emailTo = '<strong>me@somedomain.com</strong>';
	$subject = 'Contact Form Submission from '.$name;
	$sendCopy = trim($_POST['sendCopy']);
	$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
	$headers = 'From: My Site &lt;'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

	mail($emailTo, $subject, $body, $headers);

	if($sendCopy == true) {
		$subject = 'You emailed <strong>Your Name</strong>';
		$headers = 'From: <strong>Your Name</strong> &lt;<strong>noreply@somedomain.com</strong>>';
		mail($email, $subject, $body, $headers);
	}

	$emailSent = true;

}</code></pre>
<p class="note"><em>Note: Items bolded are values that you will want to change before implementing.</em></p>
<p>I personally like to have the contact form submission come from myself. That way, I just setup a filter in Gmail, and I can guarantee that it won&rsquo;t get caught in my spam filter. The second email is only sent if the user checks the checkbox to send a copy to themselves.</p>
<p><a href="http://trevordavis.net/wp-content/uploads/2009/02/contact-form.txt" class="more-link">View Entire Custom Page Template</a></p>
<h3>Creating the Page in WordPress</h3>
<p>First, you want to upload the <a href="http://trevordavis.net/wp-content/uploads/2009/02/contact-form.zip">contact-form.php</a> page template to your themes folder. Next, you will create the page in WordPress and select <strong>Contact Form</strong> as the page template.</p>
<p class="pullLeft"><img src="http://trevordavis.net/wp-content/uploads/2009/02/wordpress-page-template.png" alt="Adding WordPress page template" class="frame" height="341" width="570" /></p>
<p>Then, just publish your page and you will have your contact form. Well, the form will be usable, but we are going to add in some CSS and jQuery to finish it off.</p>
<h3>Styling the Form</h3>
<p>I recently wrote <a href="http://trevordavis.net/blog/tutorial/flexible-and-semantic-forms-with-a-little-jquery/">an article about styling forms</a>, so we are just going to stick with some basic styles:</p>
<pre><code>.screenReader { left: -9999px; position: absolute; top: -9999px; }
.thanks { background: #F2F3F6; border: 1px solid #7E8AA2; padding: 10px; }

/*****Forms*****/
ol.forms { float: left; list-style: none; margin: 0; width: 100%; }
ol.forms li {
	clear: both;
	float: left;
	margin-bottom: 18px;
	position: relative;
	width: 100%;
}
ol.forms label {
	cursor: pointer;
	display: block;
	float: left;
	font-weight: bold;
	padding-right: 20px;
	width: 100px;
}
ol.forms input, ol.forms textarea {
	border: 1px solid #7E8AA2;
	border-radius: 3px;
	font: inherit;
	-moz-border-radius: 3px;
	padding: 2px;
	-webkit-border-radius: 3px;
	width: 214px;
}
ol.forms textarea { height: 300px; width: 334px; }
ol.forms input:focus, ol.forms textarea:focus { background-color: #f2f3f6; border-color: #ff9800; }
.error { color: #f00; }
ol.forms li .error { font-size: 12px; margin-left: 20px; }
ol.forms li.textarea .error {
	display: block;
	position: absolute;
	right: 0;
	top: 0;
	width: 100px;
}
ol.forms li.screenReader { margin-bottom: 0; }
ol.forms li.buttons button {
	background: #ff9800;
	border: none;
	color: #000;
	cursor: pointer;
	font: 16px/16px "Avenir LT Std", Helvetica, Arial, sans-serif;
	overflow: hidden;
	padding: 6px 3px 3px 3px;
	text-transform: uppercase;
	width: auto;
}
ol.forms li.buttons button:hover { color: #222; }
ol.forms li.buttons button:active { left: -1px; position: relative; top: -1px; }
ol.forms li.buttons, ol.forms li.inline { float: right; width: 460px; }
ol.forms li.inline input { width: auto; }
ol.forms li.inline label { display: inline; float: none; width: auto; }</code></pre>
<p>So drop that CSS in your theme stylesheet and you will see the form start to look much better.</p>
<h3>Enhancing the form with some jQuery</h3>
<p>I have also already written about creating <a href="http://trevordavis.net/blog/tutorials/ajax-forms-with-jquery/">AJAX forms with jQuery</a>, but I thought I would specifically talk about an AJAX script for a contact form.</p>
<p>First, we want to execute our jQuery when the document is ready and the form was submitted:</p>
<pre><code>$(document).ready(function() {
	$('form#contactForm').submit(function() {

		return false;
	});
});</code></pre>
<p>Next, we want to hide any error messages if there are any and validate any required fields which are denoted with a class of <strong>requiredField</strong>:</p>
<pre><code>$('form#contactForm .error').remove();
var hasError = false;
$('.requiredField').each(function() {

});</code></pre>
<p>After that, we want to validate that the field is not empty and append an error message if it is:</p>
<pre><code>if(jQuery.trim($(this).val()) == '') {
	var labelText = $(this).prev('label').text();
	$(this).parent().append('&lt;span class="error">You forgot to enter your '+labelText+'.&lt;/span>');
	hasError = true;
}</code></pre>
<p>If the field is not empty and also has a class of <strong>email</strong>, we want to validate that the email address is valid:</p>
<pre><code> else if($(this).hasClass('email')) {
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	if(!emailReg.test(jQuery.trim($(this).val()))) {
		var labelText = $(this).prev('label').text();
		$(this).parent().append('&lt;span class="error">You entered an invalid '+labelText+'.&lt;/span>');
		hasError = true;
	}
}</code></pre>
<p>If there are no errors, then we want to replace the submit button with a loading image:</p>
<pre><code>if(!hasError) {
$('form#contactForm li.buttons button').fadeOut('normal', function() {
	$(this).parent().append('&lt;img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading&hellip;" height="31" width="31" />');
});</code></pre>
<p class="note"><em>Note: You will need to update the source of the image to wherever you upload it in your theme.</em></p>
<p>Finally, let&rsquo;s submit the form via an AJAX request, slide the form up, and show a thank you message:</p>
<pre><code>var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
	$('form#contactForm').slideUp("fast", function() {
		$(this).before('&lt;p class="thanks">&lt;strong>Thanks!&lt;/strong> Your email was successfully sent. I check my email all the time, so I should be in touch soon.&lt;/p>');
	});
});</code></pre>
<p>Take a look at the entire script:</p>
<pre><code>$(document).ready(function() {
	$('form#contactForm').submit(function() {
		$('form#contactForm .error').remove();
		var hasError = false;
		$('.requiredField').each(function() {
			if(jQuery.trim($(this).val()) == '') {
				var labelText = $(this).prev('label').text();
				$(this).parent().append('&lt;span class="error">You forgot to enter your '+labelText+'.&lt;/span>');
				hasError = true;
			} else if($(this).hasClass('email')) {
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				if(!emailReg.test(jQuery.trim($(this).val()))) {
					var labelText = $(this).prev('label').text();
					$(this).parent().append('&lt;span class="error">You entered an invalid '+labelText+'.&lt;/span>');
					hasError = true;
				}
			}
		});
		if(!hasError) {
			$('form#contactForm li.buttons button').fadeOut('normal', function() {
				$(this).parent().append('&lt;img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading&hellip;" height="31" width="31" />');
			});
			var formInput = $(this).serialize();
			$.post($(this).attr('action'),formInput, function(data){
				$('form#contactForm').slideUp("fast", function() {
					$(this).before('&lt;p class="thanks">&lt;strong>Thanks!&lt;/strong> Your email was successfully sent. I check my email all the time, so I should be in touch soon.&lt;/p>');
				});
			});
		}

		return false;

	});
});</code></pre>
<p>Just include it in the head of your document after jQuery, and you are good to go:</p>
<pre><code>&lt;script type="text/javascript" src="&lt;?php bloginfo('template_directory'); ?>/scripts/jquery.js">&lt;/script>
&lt;script type="text/javascript" src="&lt;?php bloginfo('template_directory'); ?>/scripts/contact-form.js">&lt;/script></code></pre>
<p class="note"><em>Note: You may need to change the source depending upon where you upload the files in your theme.</em></p>
<h2>Conclusion</h2>
<p class="clearfix last"><a href="http://trevordavis.net/contact-form/" class="leftSide more-link">View Demo</a> <a href="http://trevordavis.net/wp-content/uploads/2009/02/contact-form.zip" class="leftSide more-link">Download Source Files</a></p>
<p>That&rsquo;s it! Just upload the files and you&rsquo;ve got your form. Since you&rsquo;ve got the code right in front of you, it should be very easy to tweak and add on to. Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/wordpress-jquery-contact-form-without-a-plugin/feed/</wfw:commentRss>
		<slash:comments>246</slash:comments>
		</item>
		<item>
		<title>5 Ways to Instantly Write Better CSS</title>
		<link>http://trevordavis.net/blog/tutorial/5-ways-to-instantly-write-better-css/</link>
		<comments>http://trevordavis.net/blog/tutorial/5-ways-to-instantly-write-better-css/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 14:04:42 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1529</guid>
		<description><![CDATA[In my most recent article at NETTUTS: 5 Ways to Instantly Write Better CSS, I share some tips that have helped me to write better CSS.

This is definitely not me trying to tell you to code in a certain way; they are just some tips that I have found to become very useful for myself. [...]]]></description>
			<content:encoded><![CDATA[<p>In my most recent article at NETTUTS: <a href="http://nettuts.com/tutorials/html-css-techniques/5-tips-to-writing-better-css/">5 Ways to Instantly Write Better CSS</a>, I share some tips that have helped me to write better CSS.</p>
<p><span id="more-1529"></span></p>
<p>This is definitely not me trying to tell you to code in a certain way; they are just some tips that I have found to become very useful for myself. I hope you enjoy, and feel free to <a href="http://nettuts.com/tutorials/html-css-techniques/5-tips-to-writing-better-css/#add">share other tips</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/5-ways-to-instantly-write-better-css/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fixing a Twitter WordPress Plugin with jQuery</title>
		<link>http://trevordavis.net/blog/tutorial/fixing-twitter-wordpress-plugin-jquery/</link>
		<comments>http://trevordavis.net/blog/tutorial/fixing-twitter-wordpress-plugin-jquery/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 05:57:52 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1377</guid>
		<description><![CDATA[I use the fantastic Twitter for WordPress plugin on my website. Sometimes though, Twitter decides that it doesn&#8217;t want to make my tweets available. The plugin has accounted for this, and it displays No public Twitter messages when this happens. That kinda sucks though.

It&#8217;s definitely nice that the plugin doesn&#8217;t throw an error, but I [...]]]></description>
			<content:encoded><![CDATA[<p>I use the fantastic <a href="http://wordpress.org/extend/plugins/twitter-for-wordpress/">Twitter for WordPress plugin</a> on my website. Sometimes though, <a href="http://twitter.com">Twitter</a> decides that it doesn&rsquo;t want to make my tweets available. The plugin has accounted for this, and it displays <strong>No public Twitter messages</strong> when this happens. That kinda sucks though.</p>
<p><span id="more-1377"></span></p>
<p>It&rsquo;s definitely nice that the plugin doesn&rsquo;t throw an error, but I really don&rsquo;t want that message displayed on my site. So what&rsquo;s the solution? <strong>jQuery of course</strong>.</p>
<h2>When the Tweet Comes Through</h2>
<p>Here is the markup that is displayed on my site when a tweet comes through successfully:</p>
<pre><code>&lt;div id="twitterContainer">
	&lt;a class="twitter-link" href="http://twitter.com/davist11/status/1200405534">
		I feel like I'm in an episode of Seinfeld right now.
	&lt;/a>
&lt;/div></code></pre>
<h2>When the Tweet Doesn&rsquo;t Come Through</h2>
<p>This is what you end up with:</p>
<pre><code>&lt;div id="twitterContainer">
	No public Twitter messages.
&lt;/div></code></pre>
<h2>The jQuery</h2>
<p>My thinking is that I will check the contents of <strong>div#twitterContainer</strong> to see if it is <strong>No public Twitter messages</strong>. If it is, I think it would be useful to replace that text with a link to <a href="http://twitter.com/davist11">my Twitter account</a> with a message telling people to follow me.</p>
<p>So first, let&rsquo;s execute the jQuery code when the document is loaded:</p>
<pre><code>$(document).ready(function() {

});</code></pre>
<p>Next, we are going to check and see <strong>if the contents of div#twitterContainer is No public Twitter messages</strong>:</p>
<pre><code>$(document).ready(function() {
	<strong>if(jQuery.trim($('div#twitterContainer').text()) == 'No public Twitter messages.') {

	}</strong>
});</code></pre>
<p>Finally, let&rsquo;s just replace this text with a link to my Twitter feed:</p>
<pre><code>$(document).ready(function() {
	if(jQuery.trim($('div#twitterContainer').text()) == 'No public Twitter messages.') {
		<strong>$('div#twitterContainer').html('&lt;a href="http://twitter.com/davist11" class="twitter-link">Follow Me on Twitter&lt;/a>');</strong>
	}
});</code></pre>
<div class="clearfix">
<p><img src="http://trevordavis.net/wp-content/uploads/2009/02/twitter-plugin-fixed.jpg" alt="Screenshot of fixed Twitter plugin" class="rightSide frame" height="164" width="150" /><strong>That&rsquo;s it</strong>. This is just <a href="http://trevordavis.net/blog/tutorial/improving-a-flickr-plugin-with-jquery/">another example of how I have used jQuery to improve a WordPress plugin on my site</a>.</p>
<p>You can see this in action on my site, or <a href="http://trevordavis.net/play/fixing-twitter-plugin/">take a look at the demo</a>.</p>
<p><a href="http://trevordavis.net/play/fixing-twitter-plugin/" class="more-link">See Demo</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/fixing-twitter-wordpress-plugin-jquery/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Setting Body Ids in Expression Engine</title>
		<link>http://trevordavis.net/blog/tutorial/setting-body-ids-in-expression-engine/</link>
		<comments>http://trevordavis.net/blog/tutorial/setting-body-ids-in-expression-engine/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 15:08:33 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1373</guid>
		<description><![CDATA[Expression Engine has become a popular choice to power many sites. I have just begun experimenting with it, and I have been very impressed. One thing that I have been interested in determining was to figure out if I could set an id on the body like I do when building other sites. I have [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://expressionengine.com/">Expression Engine</a> has become a popular choice to power many sites. I have just begun experimenting with it, and I have been very impressed. One thing that I have been interested in determining was to figure out if I could set an id on the body like I do when building other sites. I have already written one article showing how to do this in <a href="http://trevordavis.net/blog/tutorial/set-a-body-id/">PHP and WordPress</a>, but this will show how to do it dynamically in Expression Engine.</p>
<p><span id="more-1373"></span></p>
<h2>Why are Body Ids Useful?</h2>
<p>Body ids can be useful for styling sections differently, displaying certain parts of a dynamic template, displaying current navigation states, and many other things.</p>
<h3>A Simple Example</h3>
<p>Let&rsquo;s say that I want to have my font size be 14 pixels, <strong>except on the homepage</strong>. It would be as easy as this:</p>
<pre><code>body { font-size: 14px; }
body#home { font-size: 12px; }</code></pre>
<p><strong>Pretty useful.</strong> By using body ids, we now have a unique hook for each section of the website.</p>
<h2>Why not Body Classes?</h2>
<p>I do utilize body classes as well. I typically use the body id to indicate the section, then other various items for the body classes.</p>
<h3>For Example</h3>
<p>For my own blog, I have some pages that I want to have a left gutter on it so that I can push images, quotes, etc. into the column. I also have another class that indicates when it is a blog article page. So, I can just continue to use multiple classes on the body to help me control the width and layout of the page.</p>
<p>Here is what the body element looks like on a blog article on my site:</p>
<pre><code>&lt;body id="blog" class="subpage leftGutter article"></code></pre>
<p>The <strong>subpage class</strong> just indicates that it is not the homepage. Not completely necessary since I already have a specific id on the homepage, but it can sometimes become useful.</p>
<p>The <strong>leftGutter class</strong> is used to push the content area to the right and make it narrower. Then, I can pull elements into the left-hand gutter as well.</p>
<p>The <strong>article class</strong> is useful because some of the markup for the blog entry information is the same as the homepage and archive pages. Using this class, I can be more specific with my styles to change the way that these elements are displayed on the blog article page.</p>
<p>I always try and add classes and id attributes as high up in the tree as possible. This let&rsquo;s me utilize descendant selectors in the CSS without having to add additional classes and ids lower down.</p>
<h2>Setting the Body Id in Expression Engine</h2>
<p>I want to have complete control over the body id, so I want to be able to have it set dynamically and also be able to set it statically.</p>
<p>So my thought behind this is that first, I want to check to see if the body id was set statically. When I say statically, I mean passing the variable in as an attribute on my embed statement. Next, I will then set the body id dynamically.</p>
<h3>Setting the Id Statically</h3>
<p>In order to make changes to the overall website structure simpler, I have a header template the sits in the includes template group. So in all of the other template groups, I embed the header on the page:</p>
<pre><code>{embed="includes/header"}</code></pre>
<p>Then, if for some reason I want to specifically pass in a body id, I can just change it to this:</p>
<pre><code>{embed="includes/header" <strong>body_id="contact-us"</strong>}</code></pre>
<p>So the first step in the header is to check to see if the <strong>embed:body_id</strong> variable is set:</p>
<pre><code>&lt;body
{if embed:body_id}
	id="{embed:body_id}"
{/if}
></code></pre>
<p class="note"><em>Note: Line wrapping added for readability.</em></p>
<h3>Dynamically Setting the Id</h3>
<p>If we are not statically setting the body id, we want to then do it dynamically. My thinking is that I will take advantage of Expression Engine&rsquo;s <a href="http://expressionengine.com/docs/templates/globals/url_segments.html">URL segments</a> to determine which section we are in.</p>
<p>Here is an example of URL segments using the following URL:</p>
<pre><code>http://ee.trevordavis.net/index.php/about/me/education/</code></pre>
<ul>
<li>Segment 1 = <strong>about</strong></li>
<li>Segment 2 = <strong>me</strong></li>
<li>Segment 3 = <strong>education</strong></li>
</ul>
<p>Then, we can reference each segment like so:</p>
<ul>
<li>Segment 1 = <strong>{segment_1}</strong></li>
<li>Segment 2 = <strong>{segment_2}</strong></li>
<li>Segment 3 = <strong>{segment_3}</strong></li>
</ul>
<p>So basically what we want to do is assign the body id the value of <strong>{segment_1}</strong> if it is not empty. So continuing on our example:</p>
<pre><code>&lt;body
{if embed:body_id}
	id="{embed:body_id}"
{if:elseif segment_1}
	id="{segment_1}"
{/if}
></code></pre>
<p class="note"><em>Note: Line wrapping added for readability.</em></p>
<p><strong>But wait, what about the homepage?</strong> The homepage will have nothing for the value of <strong>{segment_1}</strong>, so we can just put in an else statement:</p>
<pre><code>&lt;body
{if embed:body_id}
	id="{embed:body_id}"
{if:elseif segment_1}
	id="{segment_1}"
{if:else}
	id="home"
{/if}
></code></pre>
<p class="note"><em>Note: Line wrapping added for readability.</em></p>
<p>Here is the line of code without any line wrapping:</p>
<pre><code>&lt;body{if embed:body_id} id="{embed:body_id}"{if:elseif segment_1} id="{segment_1}"{if:else} id="home"{/if}></code></pre>
<p>I created a <a href="http://ee.trevordavis.net/index.php/">demo Expression Engine site</a> to test this functionality.</p>
<p><a href="http://ee.trevordavis.net/index.php/" class="more-link">View Demo Site</a></p>
<h2>Walking Through the Demo Site</h2>
<p>Since we have body ids for each section and an id on each list item in the navigation, I have created the current state for the navigation with a few simple line of CSS:</p>
<pre><code>body#home ul#primaryNav li#homeNav a,
body#about ul#primaryNav li#aboutNav a,
body#services ul#primaryNav li#servicesNav a,
body#contact-us ul#primaryNav li#contactNav a {
	background: #B3602D;
	border-top-color: #B3602D;
	color: #fff;
}</code></pre>
<p class="note"><em>Note: Line wrapping added for readability.</em></p>
<p>I also want to show the sidebar on all of the subpages, so I just need 1 more conditional:</p>
<pre><code>{if embed:body_id || segment_1}
	&lt;div id="sidebar">
	&lt;/div>
{/if}</code></pre>
<p>This is checking to see if {embed:body_id} or {segment_1} are not empty, and displaying the sidebar if one or both are set.</p>
<p>These are just a few examples of using a body id in Expression Engine, but the possibilities are endless.</p>
<h2>One More Thing</h2>
<p>Another thing that I was trying to figure out was how to create a variable that I could reuse in multiple embed files. So what I want to do is in my conditional statement, determine that the body id should be and assign it to a variable. Then, I want to be able to access that variable in the footer without have to use the same conditional statement.</p>
<p><strong>Is this possible?</strong> I was messing around with the <strong>{assign_variable}</strong> tag, but that didn&rsquo;t seem to do the job because it can only be used in the same template. <strong>Anyone know how to do this?</strong> I&rsquo;m relatively new to Expression Engine, so I am still learning. </p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/setting-body-ids-in-expression-engine/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>I&#8217;m a Weekly NETTUTS Writer</title>
		<link>http://trevordavis.net/blog/tutorial/im-a-weekly-nettuts-writer/</link>
		<comments>http://trevordavis.net/blog/tutorial/im-a-weekly-nettuts-writer/#comments</comments>
		<pubDate>Wed, 04 Feb 2009 02:54:43 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1438</guid>
		<description><![CDATA[As I noted in my last post, I submitted a tutorial to NETTUTS to be considered as a weekly writer. I am very happy to announce that they chose me!
In my second article, Creating a &#8220;Filterable&#8221; Portfolio with jQuery, I take a look at creating a portfolio that can be filtered by category.

This tutorial was [...]]]></description>
			<content:encoded><![CDATA[<p>As I noted in my <a href="http://trevordavis.net/blog/tutorial/exactly-how-to-create-a-custom-jquery-accordion/">last post</a>, I submitted a tutorial to <a href="http://nettuts.com/">NETTUTS</a> to be considered as a weekly writer. I am very happy to announce that <strong>they chose me</strong>!</p>
<p>In my second article, <a href="http://nettuts.com/tutorials/javascript-ajax/creating-a-filterable-portfolio-with-jquery/">Creating a &ldquo;Filterable&rdquo; Portfolio with jQuery</a>, I take a look at creating a portfolio that can be filtered by category.</p>
<p><span id="more-1438"></span></p>
<p>This tutorial was kind of inspired by the effect that I created on <a href="http://www.matrixgroup.net/portfolio/">my company&rsquo;s portfolio</a>.</p>
<h2>How will this effect my web site?</h2>
<p>Yes, I am not going to be able to write articles as frequently on my blog, but I am still going to be posting some articles. I will also post a note each week discussing my weekly NETTUTS article.</p>
<p>I hope you all enjoy the articles.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/im-a-weekly-nettuts-writer/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Exactly How to Create a Custom jQuery Accordion</title>
		<link>http://trevordavis.net/blog/tutorial/exactly-how-to-create-a-custom-jquery-accordion/</link>
		<comments>http://trevordavis.net/blog/tutorial/exactly-how-to-create-a-custom-jquery-accordion/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 21:27:38 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1328</guid>
		<description><![CDATA[Yesterday, I saw that NETTUTS was looking for another staff writer. I figured that I would give it a shot and write a tutorial about creating a custom jQuery accordion (just like the one on the sidebar of my website). Well what do you know, they published it.
]]></description>
			<content:encoded><![CDATA[<p>Yesterday, I saw that <a href="http://nettuts.com/articles/news/a-staff-writer-position-has-opened/">NETTUTS was looking for another staff writer</a>. I figured that I would give it a shot and write a tutorial about creating a custom jQuery accordion (just like the one on the sidebar of my website). Well what do you know, <a href="http://nettuts.com/tutorials/javascript-ajax/exactly-how-to-create-a-custom-jquery-accordion/">they published it</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/exactly-how-to-create-a-custom-jquery-accordion/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Use jQuery to Enhance your WordPress Comment Form</title>
		<link>http://trevordavis.net/blog/tutorial/use-jquery-to-enhance-your-wordpress-comment-form/</link>
		<comments>http://trevordavis.net/blog/tutorial/use-jquery-to-enhance-your-wordpress-comment-form/#comments</comments>
		<pubDate>Tue, 13 Jan 2009 05:47:29 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1253</guid>
		<description><![CDATA[I have already completed a couple of tutorials on forms and jQuery (Ajax Forms with jQuery and Flexible and Semantic Forms with a Little jQuery), but I wanted to show another example of using a simple jQuery script to enhance functionality. This example will be about the comment form on a WordPress powered site.

Depending upon [...]]]></description>
			<content:encoded><![CDATA[<p>I have already completed a couple of tutorials on forms and jQuery (<a href="http://trevordavis.net/blog/tutorial/ajax-forms-with-jquery/">Ajax Forms with jQuery</a> and <a href="http://trevordavis.net/blog/tutorial/flexible-and-semantic-forms-with-a-little-jquery/">Flexible and Semantic Forms with a Little jQuery</a>), but I wanted to show another example of using a simple jQuery script to enhance functionality. This example will be about the comment form on a WordPress powered site.</p>
<p><span id="more-1253"></span></p>
<p><img src="http://trevordavis.net/wp-content/uploads/2009/01/wordpress-validation.gif" alt="WordPress Validation Screenshot" width="330" height="106" class="leftSide pullLeft col6 frame" />Depending upon your configuration, WordPress will validate the comment form for required fields. In my configuration, I want to make sure that users fill in their name and email address If you submit my comment form without those, WordPress will perform server side validation.</p>
<p>But, do you really want users to see this error page? <strong>Wouldn&rsquo;t it be so much better if we used to JavaScript to validate on the client side so that they never have to leave the form</strong>?</p>
<p>I think so. Before we get started, I created <a href="http://trevordavis.net/play/wordpress-comment-form/">a sample of the WordPress comment form</a>.</p>
<p><a href="http://trevordavis.net/play/wordpress-comment-form/" class="more-link">See Example Page</a></p>
<h2>Creating the Markup</h2>
<p>I have tweaked my markup somewhat from the default WordPress comment form, so you will need to make changes to account for your markup. Here is the markup for my form:</p>
<pre><code>&lt;form action="#" method="post" id="commentform">
	&lt;p class="required">* Denotes Required Field&lt;/p>
	&lt;ol class="forms">
		&lt;li>
			&lt;label for="author">Name &lt;span class="required">*&lt;/span>&lt;/label>
			&lt;input type="text" class="requiredField" name="author" id="author" size="22" />
		&lt;/li>
		&lt;li>
			&lt;label for="email">E-Mail &lt;span class="required">*&lt;/span>&lt;/label>
			&lt;input type="text"  class="requiredField" name="email" id="email" size="22" />
		&lt;/li>
		&lt;li>
			&lt;label for="url">Website&lt;/label>
			&lt;input type="text" name="url" id="url" size="22" />
		&lt;/li>
		&lt;li class="textarea">
			&lt;label for="comment">Comments &lt;span class="required">*&lt;/span>&lt;/label>
			&lt;textarea  class="requiredField" name="comment" id="comment" cols="100%" rows="10">&lt;/textarea>
		&lt;/li>
		&lt;li class="subscribe-to-comments">
			&lt;input type="checkbox" name="subscribe" id="subscribe" value="subscribe"  />
			&lt;label for="subscribe">Notify me of followup comments via e-mail&lt;/label>
		&lt;/li>
		&lt;li class="buttons">
			&lt;button type="submit" name="submit" id="submit">Add Comment &raquo;&lt;/button>
		&lt;/li>
	&lt;/ol>
&lt;/form></code></pre>
<p>I don&rsquo;t think there is much that I need to discuss about that markup; it is pretty standard. The only thing to mention is the class name of <strong>requiredField</strong> on the form fields that I want to be required. <em>Note: I also removed the action on the form so that the sample form cannot really be submitted to the database.</em></p>
<h2>The jQuery</h2>
<p>I of course am going to show this example using jQuery, but you could create something comparable with any other JavaScript library or just with some plain old JavaScript.</p>
<p>Once the document is loaded, let&rsquo;s start by adding a function for when the comment form is submitted:</p>
<pre><code>$(document).ready(function() {
	$('form#commentform').submit(function() {
	&hellip;
	});
});</code></pre>
<p>Next, we want to remove any errors if they are showing, and create a flag that will let us know if an error has occured:</p>
<pre><code>$(document).ready(function() {
	$('form#commentform').submit(function() {
		<strong>$('form#commentform .error').remove();
		var hasError = false;</strong>
		&hellip;
	});
});</code></pre>
<p>Ok, here is where we really start to do some coding. I want to take each form field that has a class of <strong>requiredField</strong>, check to see if it is empty, copy the name of the label (<em>and remove the required asterisk</em>), traverse to the parent list item, and append the error message. Here is where we will also set the hasError flag so that we know an error has occurred:</p>
<pre><code>$(document).ready(function() {
	$('form#commentform').submit(function() {
		$('form#commentform .error').remove();
		var hasError = false;
		<strong>$('.requiredField').each(function() {
			if(jQuery.trim($(this).val()) == '') {
				var labelText = $(this).prev('label').text().replace(' *','');
				$(this).parent().append('&lt;span class="error">'+labelText+' is a required field.&lt;/span>');
				hasError = true;
			}
		});</strong>
		&hellip;
	});
});</code></pre>
<p>Finally, you want to check the <strong>hasError</strong> variable to determine whether or not you should submit the form to the server:</p>
<pre><code>$(document).ready(function() {
	$('form#commentform').submit(function() {
		$('form#commentform .error').remove();
		var hasError = false;
		$('.requiredField').each(function() {
			if(jQuery.trim($(this).val()) == '') {
				var labelText = $(this).prev('label').text().replace(' *','');
				$(this).parent().append('&lt;span class="error">'+labelText+' is a required field.&lt;/span>');
				hasError = true;
			}
		});
		<strong>if(hasError) {
			return false;
		}</strong>
	});
});</code></pre>
<p class="note"><em>Note: The end of the script is slightly different on the example form because I did not want to actually submit the form.</em></p>
<h2>Conclusion</h2>
<p>Just another simple example of how we can improve the user experience by using jQuery. Like usual, there are jQuery plugins out there that can do the same thing, but I think it is important to understand how to do things yourself. Plus, that is only 17 lines of JavaScript compared to much, much more for a plugin.</p>
<p>Anyone have any ideas on how to improve the script?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/use-jquery-to-enhance-your-wordpress-comment-form/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<item>
		<title>Using jQuery Clone</title>
		<link>http://trevordavis.net/blog/tutorial/using-jquery-clone/</link>
		<comments>http://trevordavis.net/blog/tutorial/using-jquery-clone/#comments</comments>
		<pubDate>Thu, 18 Dec 2008 14:33:35 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=943</guid>
		<description><![CDATA[I love how I can use jQuery to solve all of my problems. When I was working on a website for The Lighting of the National Christmas Tree, I had to create a page that displayed all of the ornaments. Thank god for the jQuery clone() method, which saved me loads of time and effort.

The [...]]]></description>
			<content:encoded><![CDATA[<p>I love how I can use jQuery to solve all of my problems. When I was working on a website for <a href="http://www.thenationaltree.org/">The Lighting of the National Christmas Tree</a>, I had to create a page that displayed all of the ornaments. Thank god for the jQuery <a href="http://docs.jquery.com/Manipulation/clone">clone()</a> method, which saved me loads of time and effort.</p>
<p><span id="more-943"></span></p>
<h2>The Situation</h2>
<p>I was on a tight deadline, and had to figure out some way to layout all of the state ornaments. Not to mention the fact that I had to crop and resize 56 images to 2 different sizes. Yes, I know there are only 50 states, but the US territories were included as well.</p>
<p>So the layout had to be easy enough for everyone to see all the ornaments and be able to click to get a more detailed photo and some information about the ornament. I really was not interested in creating 56 separate pages with information about each ornament, so I went scouring through the jQuery documentation to see how I could copy elements.</p>
<p>Before I get started describing what I had to do, <a href="http://trevordavis.net/play/using-jquery-clone-for-a-lightbox/">here is a demo page that I created</a>.</p>
<h2>My Solution</h2>
<p>So basically, this is what I wanted to happen when an ornament was clicked:</p>
<ol>
<li>Get the source of the larger image to be shown</li>
<li>Copy the description text about the ornament</li>
<li>Append the image and text and open it in a modal window</li>
</ol>
<p>The styling of the example is nothing special, so I will stick to explaining the script.</p>
<h3>The Script</h3>
<p>First, we want all of this to happen after the document is loaded and when the ornament links are clicked:</p>
<pre><code>$(document).ready(function() {
	$('ul.ornaments a').click(function() {
		return false;
	});
});</code></pre>
<p>Next, we want to setup the modal window with a couple of empty divs: <em>(Note: line breaks added for readability)</em></p>
<pre><code>$('body').append('&lt;div id="overlay">&lt;/div>
	&lt;div id="modal">
		&lt;div id="modalInner">
			&lt;a href="#" id="close" title="Close">Close&lt;/a>
			&lt;div id="modalImageColumn">&lt;/div>
			&lt;div id="modalTextColumn">&lt;/div>
			&lt;div class="clearing">&lt;/div>
		&lt;/div>
	&lt;/div>');</code></pre>
<p>Since IE6 doesn&rsquo;t support fixed positioning, we need to get the actual height of the page so we can apply that height to the overlay:</p>
<pre><code>if($.browser.msie &#038;&#038; $.browser.version <= 6.0) {
	var windowHeight = $(document).height();
	$('#overlay').height(windowHeight);
}</code></pre>
<p>Next, we set the opacity of the overlay, start to fade it in, position the modal window, and start to fade it in.</p>
<pre><code>$('#overlay').css('opacity', 0.5).fadeIn('fast');
$('#modal').fadeIn('slow');
var scrollPos = $(window).scrollTop() + 50;
$('div#modal').css('top',scrollPos+'px');</code></pre>
<p>The order of these things can be moved around some, but this is what I ended up doing, and everything looked good.</p>
<p>Next, we want to close and remove the modal window when the close button is clicked or the background overlay is clicked:</p>
<pre><code>$('div#modal a#close,div#overlay').bind('click', function() {
	$('div#modal').fadeOut('fast',function() {
		$('div#overlay').fadeOut('fast',function() {
			$(this).remove();
		});
		$(this).remove();
	});
	return false;
});</code></pre>
<p>Next, we grab the url of the link that was clicked, which goes to the full size image, and append the image to the modal window. Once the image has been loaded, we fade it in:</p>
<pre><code>var imgUrl = $(this).attr('href');
$('div#modalImageColumn').append('&lt;img src="'+imgUrl+'" alt="" class="frame" height="400" id="ornament" width="400" />');
$('img#ornament').load(function() {
	$(this).fadeIn();
});</code></pre>
<p>Finally, we get to use the clone() method. We target the div with the class of <strong>stateDescription</strong> that is a sibling of the link we clicked, clone it, and append it to the modal window:</p>
<pre><code>$(this).siblings('.stateDescription').clone().appendTo('div#modalTextColumn');</code></pre>
<h2>Conclusion</h2>
<p>Pretty cool stuff if I say so myself. I don&rsquo;t think there are any jQuery plugins out there that would have helped me achieve this, which is why it is important to actually understand jQuery.</p>
<p><a href="http://trevordavis.net/play/using-jquery-clone-for-a-lightbox/" class="more-link">See Demo</a></p>
<p><a href="http://trevordavis.net/wp-content/uploads/2008/12/modal.js">Here is the full script to download</a>. You can also take a look at the <a href="http://www.thenationaltree.org/visit-santa/pathway-of-peace/">final product on the National Christmas Tree site</a>.</p>
<p>But, I would encourage you to actually understand jQuery instead of just grabbing code and using it.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/using-jquery-clone/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Unobtrusive JavaScript Print Link (with jQuery)</title>
		<link>http://trevordavis.net/blog/tutorial/unobtrusive-javascript-print-link-with-jquery/</link>
		<comments>http://trevordavis.net/blog/tutorial/unobtrusive-javascript-print-link-with-jquery/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 13:30:06 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=1004</guid>
		<description><![CDATA[There are times when I have to implement designs that have print links on them. While I may think they are useless, I still have to make them work as they are a part of an approved comp. Sure, it is easy to have a link and then add an onclick event to launch the [...]]]></description>
			<content:encoded><![CDATA[<p>There are times when I have to implement designs that have print links on them. While I may think they are useless, I still have to make them work as they are a part of an approved comp. Sure, it is easy to have a link and then add an onclick event to launch the print window, but is that the right thing to do?</p>
<p><span id="more-1004"></span></p>
<p>Clicking a JavaScript print link does nothing more than launch the browser&rsquo;s print window. If a person has JavaScript disabled, nothing will happen when they click a link like this:</p>
<pre><code>&lt;a href="#" onclick="window.print(); return false;">Print&lt;/a></code></pre>
<p>Ideally, we do not want to have things on a page that do not work without JavaScript enabled. So the solution is to write the print link into the DOM using JavaScript, then attach a click event to the link. Luckily, I use jQuery on every project, so it makes the process much easier.</p>
<h2>The Solution</h2>
<p>In this example, we are going to prepend a list item with a link to an unordered list with the id of <strong>tools</strong>. Then, we attach a click event to the link we have just added to the DOM. Finally, we <strong>return false</strong> to override the action of the link.</p>
<p><strong>Here is the script:</strong></p>
<pre><code>$(document).ready(function() {
	$('ul#tools').prepend('&lt;li class="print">&lt;a href="#print">Click me to print&lt;/a>&lt;/li>');
	$('ul#tools li.print a').click(function() {
		window.print();
		return false;
	});
});</code></pre>
<p>Take a look at the <a href="http://trevordavis.net/play/javascript-print-link/">demo page</a> to see it in action. The script is nothing complex; it is just another example of using jQuery to improve a user&rsquo;s experience.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/unobtrusive-javascript-print-link-with-jquery/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>How to Preload Images When You Can&#8217;t Use CSS Sprites</title>
		<link>http://trevordavis.net/blog/tutorial/how-to-preload-images-when-you-cant-use-css-sprites/</link>
		<comments>http://trevordavis.net/blog/tutorial/how-to-preload-images-when-you-cant-use-css-sprites/#comments</comments>
		<pubDate>Wed, 12 Nov 2008 14:41:57 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=765</guid>
		<description><![CDATA[I have already shown how to use css sprites, but there are times when you just cannot use them. Sometimes you still want the benefit of preloading the image, so you have to get creative.

An Example



I have created a demo of a CSS sprite in action. The sprite has the two images sitting on top [...]]]></description>
			<content:encoded><![CDATA[<p>I have already shown <a href="http://trevordavis.net/blog/tutorial/the-6-most-important-css-techniques-you-need-to-know/#cssSprites">how to use css sprites</a>, but there are times when you just cannot use them. Sometimes you still want the benefit of preloading the image, so you have to get creative.</p>
<p><span id="more-765"></span></p>
<h2>An Example</h2>
<div class="leftSide pullLeft col1">
<a href="http://trevordavis.net/play/css-sprites/"><img src="http://trevordavis.net/wp-content/uploads/2008/11/sprite-vert.gif" alt="CSS Sprite" class="imageRight frame" height="40" width="21" /></a>
</div>
<p>I have created a <a href="http://trevordavis.net/play/css-sprites/">demo of a CSS sprite in action</a>. The sprite has the two images sitting on top of each other, and each link is using the image as a background image and then shifting the position of it when hovering.</p>
<pre><code>a.spriteVert {
	background: url(http://trevordavis.net/wp-content/uploads/2008/11/sprite-vert.gif) no-repeat top left;
	padding-left: 30px;
}
a.spriteVert:hover { background-position: bottom left; }</code></pre>
<p>It works great in the first example, but <strong>what happens if the user resizes their text?</strong> The sprite starts to break. When I am building a site, I am always thinking with the <a href="http://simplebits.com/publications/bulletproof/">bulletproof mentality of Dan Cederholm</a>, so this is just not an acceptable solution.</p>
<p>Now, we obviously couldn&rsquo;t position the images next to each other because we would still have a problem when shifting the image around.</p>
<h2>The Solution</h2>
<p>Typically when you are using CSS sprites, there is another element containing the anchor. Whether it&rsquo;s a list item, paragraph, div, etc; <strong>this solution will work unless you have a background image on that element as well</strong>.</p>
<h3>Example</h3>
<div class="leftSide pullLeft col1"><a href="http://trevordavis.net/play/css-sprites/preload-image/"><img src="http://trevordavis.net/wp-content/uploads/2008/11/sprite-hover.gif" alt="Background image for hover state" class="leftSide frame" height="20" width="21" /></a><a href="http://trevordavis.net/play/css-sprites/preload-image/"><img src="http://trevordavis.net/wp-content/uploads/2008/11/sprite-off.gif" alt="Background image for unactive state" class="leftSide frame" height="20" width="21" /></a></div>
<p>I have created a second <a href="http://trevordavis.net/play/css-sprites/preload-image/">demo that &ldquo;fixes&rdquo; the first example</a>. The idea behind it is that instead of combining the images into 1 image, you split it into 2. Then you <strong>place the image that is being shown on hover as the background image on another element</strong> (preferably a containing element), just positioned off the screen.</p>
<p>Then when you hover, you switch the background image, which has already been preloaded, so you don&rsquo;t get that &ldquo;white flicker&rdquo;. That may be a little hard to understand, so I&rsquo;ll give an example.</p>
<h4>The Markup</h4>
<pre><code>&lt;p class="spriteContainer">&lt;a href="#" class="spriteVert">Hover Over Me&lt;/a>&lt;/p>
&lt;p class="spriteContainer">&lt;a href="#" class="spriteVert spriteVert2">Hover Over Me&lt;/a>&lt;/p>
&lt;p class="spriteContainer">&lt;a href="#" class="spriteVert spriteVert3">Hover Over Me&lt;/a>&lt;/p></code></pre>
<p><em>Note: The extra classes of spriteVert2 and spriteVert3 are just used to change the font size.</em></p>
<h4>The CSS</h4>
<pre><code>p.spriteContainer {
	background: url(http://trevordavis.net/wp-content/uploads/2008/11/sprite-hover.gif) no-repeat -9999px -9999px;
}
a.spriteVert {
	background: url(http://trevordavis.net/wp-content/uploads/2008/11/sprite-off.gif) no-repeat top left;
	padding-left: 30px;
}
a.spriteVert:hover {
	background-image: url(http://trevordavis.net/wp-content/uploads/2008/11/sprite-hover.gif);
}</code></pre>
<h4>More Explanation</h4>
<p>So looking at the previous example, I am adding the background image that I want to appear on hover as the <strong>background image on the paragraph with a class of spriteContainer</strong>, and I am positioning it way off the screen.</p>
<p>Then when I hover over an anchor with a class of spriteVert, <strong>I change the background image to be the one from the paragraph</strong> with a class of spriteContainer.</p>
<h2>Conclusion</h2>
<p>While this is not as ideal as using CSS sprites because you increase the number of hits to your server, it can help to eliminate the white flicker that you get if the image is not preloaded.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/how-to-preload-images-when-you-cant-use-css-sprites/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Make Your Content Smarter With jQuery</title>
		<link>http://trevordavis.net/blog/tutorial/make-your-content-smarter-with-jquery/</link>
		<comments>http://trevordavis.net/blog/tutorial/make-your-content-smarter-with-jquery/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 04:05:44 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=588</guid>
		<description><![CDATA[At work today, we were asked by a client to add a link to download Adobe Acrobat onto every page that had a PDF linked on it. Since the site was mostly static, with some content coming from the content management system, we were not interested in adding it to all of the static pages [...]]]></description>
			<content:encoded><![CDATA[<p>At work today, we were asked by a client to add a link to download Adobe Acrobat onto every page that had a PDF linked on it. Since the site was mostly static, with some content coming from the content management system, we were not interested in adding it to all of the static pages and changing the programming of the CMS output pages.</p>
<p><span id="more-588"></span></p>
<p><a href="http://seeyouin1984.com/">My co-worker</a> and I decided that the best way to do it would be with JavaScript. Since the site was already using jQuery, our company&rsquo;s library of choice, it turned out to be quite a simple task. If you just want to get to the code, <a href="http://trevordavis.net/play/jquery-pdf-links/">take a look at the demo</a>.</p>
<h2>The Idea</h2>
<ol>
<li>We add the link to download Adobe Acrobat to the site&rsquo;s template</li>
<li>We hide the link using CSS</li>
<li>We use jQuery to see if there are any links on the page linking to a PDF</li>
<li>If there are, we use jQuery to show the link</li>
</ol>
<h2>The Execution</h2>
<p>Ok, simple enough, just add the link to the source of the document:</p>
<pre><code>&lt;p id="acrobatDownload">&lt;a href="http://www.adobe.com/products/acrobat/readstep2.html">Download Adobe Acrobat to view the PDFs on this page&lt;/a>&lt;/p></code></pre>
<p>Then, hide it with CSS:</p>
<pre><code>#acrobatDownload { display: none; }</code></pre>
<h3>The jQuery</h3>
<p>First, we want to check and see if any of the links on the page end with <strong>.pdf</strong>. Then, if there are any, we fade in the link:</p>
<pre><code>$(document).ready(function() {
	if($('a[href$=.pdf]').length > 0) {
		$('#acrobatDownload').fadeIn('slow');
	}
});
</code></pre>
<p>I have created <a href="http://trevordavis.net/play/jquery-pdf-links/">a demo page with a PDF link on it</a> to see this in action.</p>
<h2>Conclusion</h2>
<p>I can&rsquo;t even imagine how much time and hassle we saved ourselves by doing this with JavaScript. Plus, it could provide useful to someone who doesn&rsquo;t have Acrobat (although I can&rsquo;t imagine that there are many).</p>
<p>The concept is actually quite simple, and my mind is grinding away trying to think of other ways to use jQuery to do things like this.</p>
<p>Can you all think of anything?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/make-your-content-smarter-with-jquery/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>jQuery Tabbed Navigation</title>
		<link>http://trevordavis.net/blog/tutorial/jquery-tabbed-navigation/</link>
		<comments>http://trevordavis.net/blog/tutorial/jquery-tabbed-navigation/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 03:58:50 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=359</guid>
		<description><![CDATA[It seems like more and more these days, JavaScript tabbed interfaces are being used. There are plenty of scripts out there, but I think it is important to be able to do things yourself. A lot of JavaScript &#8220;plugins&#8221; that you will find online will give you way more than you really need, and you [...]]]></description>
			<content:encoded><![CDATA[<p>It seems like more and more these days, JavaScript tabbed interfaces are being used. There are plenty of scripts out there, but I think it is important to be able to do things yourself. A lot of JavaScript &ldquo;plugins&rdquo; that you will find online will give you way more than you really need, and you may understand how to use it, but you will not really understand what it is really doing.</p>
<p>First, I thought I would walk through creating a tabbed navigation script with jQuery, and then modifying it so that it works without JavaScript.</p>
<p><span id="more-359"></span></p>
<p>If you want to skip ahead, <a href="http://trevordavis.net/play/javascript-tabbed-navigation/">take a look at the sample jQuery tabbed interface</a>.</p>
<h2>The Markup</h2>
<p>I&rsquo;m going to set this up using classes so that it is possible to use this multiple times on a page. There are two different pieces to the markup: the navigation and the actual content for the tabs.</p>
<h3>The Navigation</h3>
<pre><code>&lt;ul class="tabNav">
	&lt;li class="current">&lt;a href="#">Tab 1&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Tab 2&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Tab 3&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Tab 4&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Tab 5&lt;/a>&lt;/li>
&lt;/ul></code></pre>
<p>Pretty straightforward, just an un-ordered list. The JavaScript will accommodate any number of tabs. Notice that the first tab has a class of <strong>current</strong>. This will be the class to style to show the active tab.</p>
<h3>The Tab Content</h3>
<pre><code>&lt;div class="tabContainer">
	&lt;div class="tab current">
		&hellip;Content for Tab 1&hellip;
	&lt;/div>
	&lt;div class="tab">
		&hellip;Content for Tab 2&hellip;
	&lt;/div>
	&lt;div class="tab">
		&hellip;Content for Tab 3&hellip;
	&lt;/div>
	&lt;div class="tab">
		&hellip;Content for Tab 4&hellip;
	&lt;/div>
	&lt;div class="tab">
		&hellip;Content for Tab 5&hellip;
	&lt;/div>
&lt;/div></code></pre>
<p>Again, pretty straightforward: a container and a div for each of the tabs&rsquo; content. A couple of things to note: the first tab content also has a class of <strong>current</strong>, and the tabs&rsquo; content divs need to appear in the same order as the navigation.</p>
<h2>Some Basic CSS</h2>
<p>I&rsquo;m not going to explain how I completely style my example, but I will highlight the necessary styles for the tabs to work.</p>
<p>To highlight the active tab, this is what you want to style:</p>
<pre><code>ul.tabNav li.current a { &hellip; }</code></pre>
<p>In order to hide all of the tabs&rsquo; contents except for the active tab, these are the styles that are necessary:</p>
<pre><code>div.tabContainer div.tab { display: none; }
div.tabContainer div.current { display: block; }</code></pre>
<h2>The JavaScript</h2>
<p>Ok, this is definitely the meat of the post. Since I wanted this to be as generic and simple as possible, I made heavy use of the <a href="http://docs.jquery.com/Traversing/parent">parent</a> and <a href="http://docs.jquery.com/Traversing/children">children</a> selectors.</p>
<p>So to start, we want to <strong>add onclick events to the tabs</strong>:</p>
<pre><code>$(document).ready(function(){
	$('ul.tabNav a').click(function() {
		&hellip;
		return false;
	});
});</code></pre>
<p>When each tab is clicked, we want to see which tab was clicked on so that we can show the appropriate content. So we count the previous number of siblings of the parent (the list item) and store it in the <strong>curChildIndex</strong> variable:</p>
<pre><code>$(document).ready(function(){
	$('ul.tabNav a').click(function() {
		<strong>var curChildIndex = $(this).parent().prevAll().length + 1;</strong>
		&hellip;
		return false;
	});
});</code></pre>
<p>Next, we want to remove the class of current from the currently selected tab, and add the class of current to the tab we just clicked:</p>
<pre><code>$(document).ready(function(){
	$('ul.tabNav a').click(function() {
		var curChildIndex = $(this).parent().prevAll().length + 1;
		<strong>$(this).parent().parent().children('.current').removeClass('current');
		$(this).parent().addClass('current');</strong>
		&hellip;
		return false;
	});
});</code></pre>
<p>The final step is to hide the tab content that is currently showing and to show the tab content that matches the tab that was just clicked on. This is where we will make use of the <strong>curChildIndex</strong> variable and the <a href="http://docs.jquery.com/Selectors/nthChild">nth Child Selector</a>:</p>
<pre><code>$(document).ready(function(){
	$('ul.tabNav a').click(function() {
		var curChildIndex = $(this).parent().prevAll().length + 1;
		$(this).parent().parent().children('.current').removeClass('current');
		$(this).parent().addClass('current');
		<strong>$(this).parent().parent().next('.tabContainer').children('.current').slideUp('fast',function() {
			$(this).removeClass('current');
			$(this).parent().children('div:nth-child('+curChildIndex+')').slideDown('normal',function() {
				$(this).addClass('current');
			});
		});</strong>
		return false;
	});
});</code></pre>
<p>The previous snippet of the code is traversing from the clicked tab ,<strong>(this)</strong>, to the current content that has a class of <strong>current</strong>, sliding that up, and removing the class of current. Once that is complete, we are selecting the tab content that matches the tab clicked, sliding it down, and adding the class of current.</p>
<p><a href="http://trevordavis.net/play/javascript-tabbed-navigation/">Take a look at the sample jQuery tabbed interface</a> to see it in action.</p>
<h2>Making it Work for Non-JavaScript Users</h2>
<p>Now, that works great, but what about people who don&rsquo;t have JavaScript enabled? Sure it&rsquo;s a very small number, but we still want to account for those people.</p>
<p>Most other JavaScript tab scripts use JavaScript to hide the non-active tab content sections or to write in the tabbed navigation, but then you get that flash of changing content. My idea is to use CSS to hide the non active tab content (which I discussed earlier) and pass a parameter into the URL to select which tab to show.</p>
<h3>The Code</h3>
<p>Below is the new code for the tab navigation:</p>
<pre><code>&lt;ul class="tabNav">
	&lt;li&lt;?php if(!isset($_GET['tab'])) echo ' class="current"';?>>&lt;a href="">Tab 1&lt;/a>&lt;/li>
	&lt;li&lt;?php if(isset($_GET['tab']) &#038;&#038; $_GET['tab'] == 2) echo ' class="current"';?>>&lt;a href="?tab=2">Tab 2&lt;/a>&lt;/li>
	&lt;li&lt;?php if(isset($_GET['tab']) &#038;&#038; $_GET['tab'] == 3) echo ' class="current"';?>>&lt;a href="?tab=3">Tab 3&lt;/a>&lt;/li>
	&lt;li&lt;?php if(isset($_GET['tab']) &#038;&#038; $_GET['tab'] == 4) echo ' class="current"';?>>&lt;a href="?tab=4">Tab 4&lt;/a>&lt;/li>
	&lt;li&lt;?php if(isset($_GET['tab']) &#038;&#038; $_GET['tab'] == 5) echo ' class="current"';?>>&lt;a href="?tab=5">Tab 5&lt;/a>&lt;/li>
&lt;/ul></code></pre>
<p>Basically, I am checking to see if the variable <strong>tab</strong> is set in the URL, and determining the value of it. I also use the same logic for the tab content. <a href="http://trevordavis.net/play/javascript-tabbed-navigation/?tab=3">This is the example page with tab 3 displaying</a>. So basically, if the user does not have JavaScript, it would reload the entire page and display the correct tab.</p>
<h2>Conclusion</h2>
<p>This was just a simple example of jQuery, and the possibilities are endless. Instead of being so quick to use a plugin or someone&rsquo;s code, try to do it yourself. You will become a much better programmer because of it. Even if you aren&rsquo;t doing things as efficiently as possible, you will learn something new every time.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/jquery-tabbed-navigation/feed/</wfw:commentRss>
		<slash:comments>91</slash:comments>
		</item>
		<item>
		<title>Flexible and Semantic Forms with a Little jQuery</title>
		<link>http://trevordavis.net/blog/tutorial/flexible-and-semantic-forms-with-a-little-jquery/</link>
		<comments>http://trevordavis.net/blog/tutorial/flexible-and-semantic-forms-with-a-little-jquery/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 03:20:45 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=251</guid>
		<description><![CDATA[While they may not be that pretty, forms are one of the most important parts of a web site. I have already written an article on CSS Forms, that was over a year ago, and I have developed much better techniques.
There are other great resources for information about form design, and I will take this [...]]]></description>
			<content:encoded><![CDATA[<p>While they may not be that pretty, forms are one of the most important parts of a web site. <a href="http://trevordavis.net/blog/tutorial/css-forms/">I have already written an article on CSS Forms</a>, that was over a year ago, and I have developed much better techniques.</p>
<p>There are other <a href="http://www.lukew.com/resources/articles/web_forms.html">great resources for information about form design</a>, and I will take this information into account when I am showing the flexibility of my method of marking up and styling forms.</p>
<p><span id="more-251"></span></p>
<h2>The Markup</h2>
<p>After previously using a <strong>definition list</strong> to mark up my forms, I have switched to using an <strong>ordered list</strong> now. I switched for two main reasons:</p>
<ul>
<li>The list item of the ordered list provides a containing clearing element that the definition list does not provide.</li>
<li>Semantically, it just makes more sense. A form is really just a list of form fields to fill out. Forms are typically meant to be filled out in order, hence the ordered list instead of un-ordered list (I think this could be debated, but in the long run, either one is more semantic than anything else).</li>
</ul>
<p>I have decided to create just a <a href="http://trevordavis.net/play/forms-revisited/">simple un-styled form</a> to use as an example. Here is what the markup of the page is:</p>
<pre><code>&lt;ol class="forms">
	&lt;li>&lt;label for="name">Name&lt;/label>&lt;input type="text"name="name" id="name" />&lt;/li>
	&lt;li>&lt;label for="email">Email&lt;/label>&lt;input type="text" name="email" id="email" />&lt;/li>
	&lt;li>&lt;label for="city">City&lt;/label>&lt;input type="text" name="city" id="city" />&lt;/li>
	&lt;li>&lt;label for="state">State&lt;/label>&lt;input type="text" name="state" id="state" />&lt;/li>
	&lt;li>&lt;label for="zip">Zip&lt;/label>&lt;input type="text" name="zip" id="zip" />&lt;/li>
	&lt;li class="grouping">&lt;label>Sign Up for the Following&lt;/label>
		&lt;ul>
			&lt;li>&lt;input type="checkbox" name="info1" id="info1" />&lt;label for="info1">Information 1&lt;/label>&lt;/li>
			&lt;li>&lt;input type="checkbox" name="info2" id="info2" />&lt;label for="info2">Information 2&lt;/label>&lt;/li>
			&lt;li>&lt;input type="checkbox" name="info3" id="info3" />&lt;label for="info3">Information 3&lt;/label>&lt;/li>
		&lt;/ul>
	&lt;/li>
	&lt;li>&lt;label for="message">Message&lt;/label>&lt;textarea name="message" id="message">&lt;/textarea>&lt;/li>
	&lt;li class="buttons">&lt;button type="submit" name="submit" id="submit">Submit&lt;/button>&lt;/li>
&lt;/ol></code></pre>
<p>Even without any style applied, the form is still completely usable.</p>
<h2>Styling the Forms</h2>
<p>There are really 3 main styles of laying out forms:</p>
<ul>
<li>Labels above the form field</li>
<li>Labels to the side of the form field, jagged right</li>
<li>Labels to the side of the form field, jagged left</li>
</ul>
<p>Again, like I said, I am not going to go through the pros and cons of each method, I am going to show how easy it is to switch between the methods using my markup.</p>
<h3>Labels Above the Form Field</h3>
<p>This is by far the easiest method. Here is the CSS used to style my <a href="http://trevordavis.net/play/forms-revisited/forms-styled-labels-stacked/">example form</a>:</p>
<pre><code>ol.forms { float: left; list-style: none; width: 100%; }
ol.forms li {
	clear: both;
	float: left;
	margin: 0 0 10px;
	width: 100%;
}
ol.forms label { cursor: pointer; display: block; font-weight: bold; }
ol.forms input, ol.forms textarea {
	font: inherit;
	padding: 2px;
	width: 300px;
}
ol.forms textarea { height: 250px; }
ol.forms li.grouping { margin-bottom: 0; }
ol.forms li.grouping ul { list-style: none; }
ol.forms li.grouping ul label {
	display: inline;
	font-weight: normal;
	margin: 0 0 0 10px;
}
ol.forms li.grouping ul input { width: auto; }</code></pre>
<p>Really nothing too complicated. In my opinion, I don&rsquo;t like stacking the label over the form field; I think it just makes the form too long.</p>
<h3>Labels to the Side of the Form Field, Jagged Right</h3>
<p>I like this layout of forms the best. I think it presents the form in a clear way so that you can just scan right through the form fields. With just a few changes to the CSS, you can float the labels to the left of the form fields. The changes are marked in bold:</p>
<pre><code>ol.forms { float: left; list-style: none; width: 100%; }
ol.forms li {
	clear: both;
	float: left;
	margin: 0 0 10px;
	width: 100%;
}
ol.forms label {
	cursor: pointer;
	display: block;
	<strong>float: left;</strong>
	font-weight: bold;
	<strong>margin: 0 10px 0 0;
	width: 90px;</strong>
}
ol.forms input, ol.forms textarea {
	font: inherit;
	padding: 2px;
	width: 300px;
}
ol.forms textarea { height: 250px; }
<strong>ol.forms li.grouping label { margin: 0; width: auto; }</strong>
ol.forms li.grouping { margin-bottom: 0; }
ol.forms li.grouping ul { list-style: none; <strong>margin-left: 100px;</strong> }
ol.forms li.grouping ul label {
	display: inline;
	<strong>float: none;</strong>
	font-weight: normal;
	margin: 0 0 0 10px;
	<strong>width: auto;</strong>
}
ol.forms li.grouping ul input { width: auto; }
<strong>ol.forms li.buttons { float: none; margin-left: 100px; width: auto; }</strong></code></pre>
<p><a href="http://trevordavis.net/play/forms-revisited/forms-styled-labels-left/">Take a look at the example with the fields on the left</a>. Depending upon your label length, you may need to increase the width of the labels so that it does not span more than one line, but that is an easy enough change.</p>
<h3>Labels to the Side of the Form Field, Jagged Left</h3>
<p>Now with two changes to the CSS, you can easily switch to having the labels jagged left, which puts them closer to the form input. The changes needed are highlighted in bold:</p>
<pre><code>ol.forms label {
	cursor: pointer;
	display: block;
	float: left;
	font-weight: bold;
	margin: 0 10px 0 0;
	<strong>text-align: right;</strong>
	width: 90px;
}
ol.forms li.grouping label { margin: 0; <strong>text-align: left;</strong> width: auto; }</code></pre>
<p><a href="http://trevordavis.net/play/forms-revisited/forms-styled-labels-right/">Here is the example of the form with the labels jagged left</a>.</p>
<h3>Taking it a Step Further with More CSS and a Little jQuery</h3>
<p>Since I like the form layout with labels to the side and jagged right, I am going to use <a href="http://trevordavis.net/play/forms-revisited/forms-styled-labels-left/">this one</a> to customize the display a little, and then add in some jQuery functionality.</p>
<h4>Improving the Display</h4>
<p>When looking at the form, it may be confusing to have all form fields be the same width. It is helpful to the user to modify the width to suit the data that will be entered.</p>
<p>For example, there is no reason that the zip code, city, and state fields should be so long, so let&rsquo;s add a class to each one to shorten it to the length of the data that will probably be entered. Here is the modified markup:</p>
<pre><code>&lt;li>
	&lt;label for="city">City&lt;/label>
	&lt;input type="text" name="city" id="city" class="medium" />
&lt;/li>
&lt;li>
	&lt;label for="state">State&lt;/label>
	&lt;input type="text" name="state" id="state" class="small" />
&lt;/li>
&lt;li>
	&lt;label for="zip">Zip&lt;/label>
	&lt;input type="text" name="zip" id="zip" class="extraSmall" />
&lt;/li></code></pre>
<p>Then we just have to add those 3 classes to the CSS:</p>
<pre><code>ol.forms .extraSmall { width: 50px; }
ol.forms .small { width: 100px; }
ol.forms .medium { width: 150px; }</code></pre>
<p>Here is what <a href="http://trevordavis.net/play/forms-revisited/forms-styled-labels-left-customized-more/">the form looks like with that little bit of extra style</a>. I also added in some help text, a notation for required fields, and the associated CSS; so take a look at the code to see that.</p>
<h4>Adding a Little jQuery</h4>
<p>Obviously you have read my article about <a href="http://trevordavis.net/blog/tutorial/ajax-forms-with-jquery/">AJAX forms with jQuery</a>, which discusses how to add AJAX functionality to a form in a degradable way. So the following code assumes that you are going to be doing server side validation of the form as well.</p>
<p>Since there are required fields in this form, I add a class of <strong>required</strong> to the form and to each parent list item of required input fields.</p>
<p>First, we want our JavaScript to execute when the form with a class of required is submitted:</p>
<pre><code>$(document).ready(function() {
	$('form.required').submit(function() {
		&hellip;
	});
});</code></pre>
<p>If there are any error messages still displaying from before, we want to hide them. Also, let&rsquo;s disable the submit button so just in case, the form cannot be submitted twice. I am also creating a variable that I will be using later to determine if there is an error or not:</p>
<pre><code>$(document).ready(function() {
	$('form.required').submit(function() {
		<strong>$('form.required span.error').remove();
		$('form.required li.buttons button').attr('disabled','disabled');
		var hasError = false;</strong>
	});
});</code></pre>
<p>Now, we want to check each form field that has a parent list item with a class of <strong>required</strong>:</p>
<pre><code>$(document).ready(function() {
	$('form.required').submit(function() {
		$('form.required span.error').remove();
		$('form.required li.buttons button').attr('disabled','disabled');
		var hasError = false;

		<strong>jQuery.each($('form.required ol.forms li.required'),function() {
			&hellip;
		});</strong>
	});
});</code></pre>
<p>There are a lot of other jQuery plugins that validate forms, but most of the time, it will just alert the user that the field is required. Instead of doing that, I am going to grab the text from the label element and display that in the error message:</p>
<pre><code>$(document).ready(function() {
	$('form.required').submit(function() {
		$('form.required span.error').remove();
		$('form.required li.buttons button').attr('disabled','disabled');
		var hasError = false;

		jQuery.each($('form.required ol.forms li.required'),function() {
			<strong>var labelText = $(this).children('label').text();
			labelText = labelText.replace(' *','');</strong>
		});
	});
});</code></pre>
<p>Now, we have two different structures of form fields for each list item: a single form field and a grouping of checkboxes or radio buttons. We have to do things a little bit different for each one:</p>
<pre><code>$(document).ready(function() {
	$('form.required').submit(function() {
		$('form.required span.error').remove();
		$('form.required li.buttons button').attr('disabled','disabled');
		var hasError = false;

		jQuery.each($('form.required ol.forms li.required'),function() {
			var labelText = $(this).children('label').text();
			labelText = labelText.replace(' *','');

			<strong>if($(this).hasClass('grouping')) {
				&hellip;
			} else {
				&hellip;
			}</strong>
		});
	});
});</code></pre>
<p>First, let&rsquo;s focus on the case when there is a grouping. We want to loop through each input and see if it is checked. If it is, we just increment a counter. Then, if the counter equals zero, meaning we have no fields checked, we display an error message:</p>
<pre><code>$(document).ready(function() {
	$('form.required').submit(function() {
		$('form.required span.error').remove();
		$('form.required li.buttons button').attr('disabled','disabled');
		var hasError = false;

		jQuery.each($('form.required ol.forms li.required'),function() {
			var labelText = $(this).children('label').text();
			labelText = labelText.replace(' *','');

			if($(this).hasClass('grouping')) {
				<strong>var numSelected = 0;
				jQuery.each($(this).find('input'),function() {
					if($(this).attr('checked') == true) {
						numSelected++;
					}
				});

				if(numSelected == 0) {
					$(this).append('&lt;span class="error">You must select from '+labelText+'.&lt;/span>');
					hasError = true;
				}</strong>
			} else {
				&hellip;
			}
		});
	});
});</code></pre>
<p>That seems easy enough, and it&rsquo;s even easier for the single input fields. We just check to see if the value is empty, and if it is, display the error message:</p>
<pre><code>$(document).ready(function() {
	$('form.required').submit(function() {
		$('form.required span.error').remove();
		$('form.required li.buttons button').attr('disabled','disabled');
		var hasError = false;

		jQuery.each($('form.required ol.forms li.required'),function() {
			var labelText = $(this).children('label').text();
			labelText = labelText.replace(' *','');

			if($(this).hasClass('grouping')) {
				var numSelected = 0;
				jQuery.each($(this).find('input'),function() {
					if($(this).attr('checked') == true) {
						numSelected++;
					}
				});

				if(numSelected == 0) {
					$(this).append('&lt;span class="error">You must select from '+labelText+'.&lt;/span>');
					hasError = true;
				}
			} else {
				<strong>if(jQuery.trim($(this).children('input, textarea').val()) == '') {
					$(this).append('&lt;span class="error">Please enter your '+labelText+'.&lt;/span>');
					hasError = true;
				}</strong>
			}
		});
	});
});</code></pre>
<p>To finish up, we just check to see if the <code><strong>hasError</strong></code> variable is true. Since this is just a demo form, I just add an alert if the form would submit successfully:</p>
<pre><code>$(document).ready(function() {
	$('form.required').submit(function() {
		$('form.required span.error').remove();
		$('form.required li.buttons button').attr('disabled','disabled');
		var hasError = false;

		jQuery.each($('form.required ol.forms li.required'),function() {
			var labelText = $(this).children('label').text();
			labelText = labelText.replace(' *','');

			if($(this).hasClass('grouping')) {
				var numSelected = 0;
				jQuery.each($(this).find('input'),function() {
					if($(this).attr('checked') == true) {
						numSelected++;
					}
				});

				if(numSelected == 0) {
					$(this).append('&lt;span class="error">You must select from '+labelText+'.&lt;/span>');
					hasError = true;
				}
			} else {
				if(jQuery.trim($(this).children('input, textarea').val()) == '') {
					$(this).append('&lt;span class="error">Please enter your '+labelText+'.&lt;/span>');
					hasError = true;
				}
			}
		});

		<strong>if(hasError) {
			$('form.required li.buttons button').removeAttr('disabled');
			return false;
		} else {
			alert('The form would submit now');
			$('form.required li.buttons button').removeAttr('disabled'); //Remove this line if using for real
			return false; //Change this to true when using it for real
		}</strong>
	});
});</code></pre>
<p>Go ahead and take a look at the <a href="http://trevordavis.net/play/forms-revisited/forms-styled-labels-left-customized-more/">demo form</a> to see it in action.</p>
<h2>Conclusion</h2>
<p>With a well structured form, you can easily customize it to your liking with just a little bit of CSS. Then, by using some custom jQuery code, you can easily customize how you would like to have the form validation appear.</p>
<p>With a little more work, you could easily add in validation for things like form elements expecting an email address, zip codes, phone numbers, etc. I will have to save that for another post since this one is quite long.</p>
<p>What do you all think? How do you structure your forms? Which layout of forms do you prefer and why?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/flexible-and-semantic-forms-with-a-little-jquery/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>WordPress Tips and Ideas Learned From Implementation</title>
		<link>http://trevordavis.net/blog/tutorial/wordpress-tips-and-ideas-learned-from-implementation/</link>
		<comments>http://trevordavis.net/blog/tutorial/wordpress-tips-and-ideas-learned-from-implementation/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 02:22:43 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=231</guid>
		<description><![CDATA[Recently, I had to slice and implement a blog for the CEO of my company. I decided to go with WordPress because that is what I have become enamored with recently, when I created a job board using it. I used some features of WordPress that I had never used before, so I figured I [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I had to slice and implement <a href="http://www.thematrixfiles.net/">a blog for the CEO of my company</a>. I decided to go with WordPress because that is what I have become enamored with recently, when <a href="http://www.wirelesscareer.com/">I created a job board</a> using it. I used some features of WordPress that I had never used before, so I figured I would talk about them so that others could learn how to use them as well.</p>
<p><span id="more-231"></span></p>
<h2>Multiple Loops</h2>
<p>The blog contained a main blog section, along with a &ldquo;Favorites&rdquo; section in the sidebar, that would be used to list anything: favorite websites, books, etc. I didn&rsquo;t think that using just the basic WordPress blogroll or a third party bookmarking site would give the CEO enough flexibility to mark whatever she wanted as a favorite. So I decided to just create a separate category for Favorites.</p>
<p>In the footer of the site, there is also information about the last 6 projects that we had worked on. I definitely did not want those to be static. Since we complete projects almost daily, I wanted &ldquo;non-technical&rdquo; people to be able to update them. So I decided to create a separate category for those.</p>
<p>So in total, I had 3 categories: Blog, Favorites, and Projects.</p>
<p>I figured I would just end up having the main loop in the content area, a loop in the sidebar, and a loop in the footer. I had never really done a site with multiple loops, but after reading <a href="http://codex.wordpress.org/The_Loop#Multiple_Loops">the documentation</a>, it didn&rsquo;t look too complicated. So the key to having multiple loops is to use the <a href="http://codex.wordpress.org/Template_Tags/query_posts">query_posts</a> template tag.</p>
<h3>The Main Blog Loop</h3>
<p>The Blog category has an id of 1. So all you have to do is call the query_posts template tag before you loop through the entries:</p>
<pre><code>&lt;?php query_posts('cat=1');
	if (have_posts()) :
		while (have_posts()) : the_post(); ?>
			&hellip;
		&lt;?php endwhile;
	endif; ?></code></pre>
<p>Then the Favorites and Project categories are basically the same, you just plug in the correct category id into the <strong>query_posts</strong> template tag.</p>
<h3>Paging with Multiple Loops</h3>
<p>So since we are using the <strong>query_posts</strong> template tag, it messes up the paging of the main loop. So, in the main blog loop, we need to use the ternary operator to add in the paging argument:</p>
<pre><code>&lt;?php
	$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
	query_posts("cat=1&#038;paged=$paged");
?></code></pre>
<p>So those two lines would replace the previous call to the <strong>query_posts</strong> template tag that we used for the main loop.</p>
<h2>Read More Links</h2>
<p>When I had first implemented the blog, we were using the read more links (whenever they were added into the post) for all posts. Later in the implementation process, I was told that the most recent article should always show the full post.</p>
<p>I wasn&rsquo;t sure how the heck I could do that, but after some Googling I figured it out. Basically what we need to do is just create a simple counter to see if we are on the first post. If we are, we set a global $more variable equal to 1. So I define the $count variable and set it equal to 1, then I have this at the beginning of the main loop:</p>
<pre><code>&lt;?php
if (is_home()) {
	global $more;
	if($count == 1) $more = 1;
	else $more = 0;
	$count++;
}
?></code></pre>
<h3>Wait a Minute&hellip;</h3>
<p>So I was all ready to publish this article, when I found out today that the first article on my CEO&rsquo;s blog was still showing the read more link. From what I discovered, it looked like both the <strong>is_home()</strong> and <strong>is_front_page()</strong> conditional tags were not registering as true when on the homepage. For the life of me, I could not figure out why this was happening.</p>
<p>So this was a little bit of a hacky solution, but it was all that I could think of quickly. I had this code before the loop:</p>
<pre><code>&lt;?php
	if($_SERVER['REQUEST_URI'] == '/') {
		$isHomepage = true;
	}
?></code></pre>
<p>So essentially, I was setting up my own flag to see if it was the homepage. What that is doing is checking the URL to see if it is the root of the site or not. Then I modifed the if statement in my other code to be:</p>
<pre><code>&lt;?php
	if (isset($isHomepage) &#038;&#038; $isHomepage = true) {
		global $more;
		if($count == 1) $more = 1;
		else $more = 0;
		$count++;
	}
?></code></pre>
<p>I&rsquo;m not sure if there is a better solution, but I think the reason the <strong>is_home()</strong> and <strong>is_front_page()</strong> conditions don&rsquo;t work is because of calling the <strong>query_posts</strong> template tag, because they worked before the call.</p>
<h2>Custom Fields</h2>
<p>I had used custom fields before, and they are amazingly powerful in being able to extend WordPress functionality. For my CEO&rsquo;s blog, I used 4 custom fields:</p>
<ul>
<li>favoriteThumbnail</li>
<li>favoriteUrl</li>
<li>projectThumbnail</li>
<li>projectUrl</li>
</ul>
<h3>Favorites&rsquo; Custom Fields</h3>
<p>The favorites are supposed to be little blurbs about something that my CEO likes, whether it is a book, website, etc. So the idea is that it is not supposed to be a full blog post, just a little blurb. So instead of linking to the WordPress post, we link to the <strong>favoriteUrl</strong> custom field. Here is how the favoriteUrl custom field is being used (this is called within The Loop):</p>
<pre><code>&lt;?php
$favoriteUrl = get_post_meta($post->ID, "favoriteUrl", true);
if($favoriteUrl != '') { ?>
	&lt;a href="&lt;?=$favoriteUrl ?>" class="heading">&lt;strong>&lt;?php the_title(); ?>&lt;/strong>&lt;/a>
&lt;?php } else { ?>
	&lt;strong class="heading">&lt;?php the_title(); ?>&lt;/a>
&lt;?php } ?></code></pre>
<p>So basically what I am doing there is first calling in the favoriteUrl custom field and assigning it to the $favoriteUrl variable. Then, I check to make sure it is not empty (meaning the custom field was not entered). If it is entered, I output the link to the URL. If not, I still do not link to the WordPress post, I just display the title in bold.</p>
<p>The favoriteThumbnail is pretty self explanatory and is called in the same way as the favoriteUrl. The reason I wanted to use a custom field for the thumbnail instead of just adding the image to the post content is because the design called for the image to be floated next to the title and because I wanted to link the image to the favoriteUrl. This way, when my CEO is adding a favorite, she does not have to worry about floating the image and linking it to the favoriteUrl.</p>
<h3>Projects&rsquo; Custom Fields</h3>
<p>Both of the Projects&rsquo; custom fields are used similarly to the Favorities&rsquo; custom fields. The projectThumbnail custom field is just used to show the most recent 6 projects in the footer. Nothing complicated, just showing and linking the photo to the WordPress post.</p>
<p>Until our new company website gets launched, we are linking to the short WordPress post which gives a little description about the project. The projectUrl outputs the URL to the project at the end of the post. Once our company website is finished, I will just modify the custom field to link directly from the footer to its respective page in our portfolio.</p>
<h2>Conclusion</h2>
<p>I really enjoyed doing this implementation. While it was just a simple blog, it is always great to learn a couple of new tricks/techniques. Any other WordPress tips that you have found useful?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/wordpress-tips-and-ideas-learned-from-implementation/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>jQuery Table Striping Bug</title>
		<link>http://trevordavis.net/blog/tutorial/jquery-table-striping-bug/</link>
		<comments>http://trevordavis.net/blog/tutorial/jquery-table-striping-bug/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 03:35:58 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=237</guid>
		<description><![CDATA[I have been using jQuery to do table striping, and up until today, I have not had any problems with it.
I had just been using the :even and :odd selectors to add classes to each table row.

Here is the code that I have been using:
$(document).ready(function(){
	$("table.striped tbody tr:odd").addClass("odd");
	$("table.striped tbody tr:even").addClass("even");
});
Seems easy enough. Then I just styled [...]]]></description>
			<content:encoded><![CDATA[<p>I have been using <a href="http://jquery.com/">jQuery</a> to do table striping, and up until today, I have not had any problems with it.</p>
<p>I had just been using the <a href="http://docs.jquery.com/Selectors/even">:even</a> and <a href="http://docs.jquery.com/Selectors/odd">:odd</a> selectors to add classes to each table row.</p>
<p><span id="more-237"></span></p>
<p>Here is the code that I have been using:</p>
<pre><code>$(document).ready(function(){
	$("table.striped tbody tr:odd").addClass("odd");
	$("table.striped tbody tr:even").addClass("even");
});</code></pre>
<p>Seems easy enough. Then I just styled the odd table rows like so:</p>
<pre><code>table.striped tr.odd td { background-color: #f0f0f4; }</code></pre>
<p>One thing to note is that the <strong>:even</strong> and <strong>:odd</strong> selectors are zero-indexed, so the <strong>first table row will have a class of even, and not odd</strong>. <a href="http://trevordavis.net/play/jquery-table-striping/">Here is an example showing this simple striping</a>.</p>
<h2>Multiple Striped Instances</h2>
<p>The situation that I had today had two different tables that were being striped. So based on the code, you would think that there wouldn&rsquo;t be a problem. <a href="http://trevordavis.net/play/jquery-table-striping/multiple-striping-instances/">Here is the example with two striped tables on the same page</a>.</p>
<p>Weird, so it looks like the first table row in the second striped table has a class of even instead of odd. I thought that the client may not like that because the two tables were not consistent, so I tried to think of another way to do the striping.</p>
<h2>The nth Child</h2>
<p>So based on the documentation, it looks like <a href="http://docs.jquery.com/Selectors/nthChild#index">the nth child selector</a> would be the solution. I just modified my JavaScript like so:</p>
<pre><code>$(document).ready(function(){
	$("table.striped tbody tr:nth-child(odd)").addClass("odd");
	$("table.striped tbody tr:nth-child(even)").addClass("even");
});</code></pre>
<p>As a note, <strong>the nth child selector is not zero indexed</strong>, so the first table row will have a class of odd instead of even. <a href="http://trevordavis.net/play/jquery-table-striping/using-nth-child/">Here is the fixed example</a>.</p>
<h2>Conclusion</h2>
<p>From what I can tell, this does not appear to be a browser problem, but a bug in jQuery. I have checked this in Firefox, Safari, IE6 and IE7.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/jquery-table-striping-bug/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Improving a Flickr Plugin with jQuery</title>
		<link>http://trevordavis.net/blog/tutorial/improving-a-flickr-plugin-with-jquery/</link>
		<comments>http://trevordavis.net/blog/tutorial/improving-a-flickr-plugin-with-jquery/#comments</comments>
		<pubDate>Fri, 06 Jun 2008 03:47:54 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=226</guid>
		<description><![CDATA[For a while, I have been using the flickrRSS WordPress plugin to show my recent flickr photos in the footer of my site. Since I have become more comfortable using jQuery, I thought I would use it to make the plugin better.

I created a demo page. to see what the markup generated from the plugin [...]]]></description>
			<content:encoded><![CDATA[<p>For a while, I have been using the <a href="http://wordpress.org/extend/plugins/flickr-rss/">flickrRSS</a> WordPress plugin to show my recent flickr photos in the <a href="http://trevordavis.net/#flickr">footer of my site</a>. Since I have become more comfortable using <a href="http://jquery.com/">jQuery</a>, I thought I would use it to make the plugin better.</p>
<p><span id="more-226"></span></p>
<p>I created a <a href="http://trevordavis.net/play/wordpress-flickr-plugin/">demo page</a>. to see what the markup generated from the plugin normally is. The markup is just an unordered list, and I have done some basic CSS so that it looks halfway decent.</p>
<p>Each photo just links to the original Flickr page with the photo on it. I kind of didn&rsquo;t like that because if someone wanted to see the larger version, they would have to leave my site just to see it.</p>
<p><a href="http://farm3.static.flickr.com/2123/2543094667_2ddfec7c73_s.jpg"><img src="http://farm3.static.flickr.com/2123/2543094667_2ddfec7c73_s.jpg" alt="I Love My Birthday Present" class="imageRight frame" height="75" width="75" /></a></p>
<h2>Digging into the Flickr Photos</h2>
<p>If we take a look at the square image of me hugging my new TV, we can see that it is 75&#215;75. Now if we take a closer look at the filename <strong>2543094667_2ddfec7c73_s.jpg</strong>, we see that there is a _s at the end. Let&rsquo;s take a look at the other photo sizes there are:</p>
<ul>
<li><a href="http://farm3.static.flickr.com/2123/2543094667_2ddfec7c73_t.jpg" rel="lightbox[set]">Thumbnail</a>: _t.jpg</li>
<li><a href="http://farm3.static.flickr.com/2123/2543094667_2ddfec7c73_m.jpg" rel="lightbox[set]">Small</a>: _m.jpg</li>
<li><a href="http://farm3.static.flickr.com/2123/2543094667_2ddfec7c73.jpg" rel="lightbox[set]">Medium</a>: .jpg</li>
<li><a href="http://farm3.static.flickr.com/2123/2543094667_2ddfec7c73_b.jpg" rel="lightbox[set]">Large</a>: _o.jpg</li>
</ul>
<p>The medium sized photo looks like a nice size to display. What if instead of linking the small square photos to their respective Flickr page, we open the medium sized photo in a lightbox.</p>
<h2>Lightbox</h2>
<p>The lightbox that I use is a hacked up version of the <a href="http://famspam.com/facebox">Facebox script</a>. I modified it a little to use table-less markup and for the entire page to grey out. The lightbox is launched by setting the <strong>rel</strong> attribute equal to <strong>lightbox</strong>.</p>
<p>Another modification I would like to make is to enable the lightbox to work in sets. Kind of like the <a href="http://www.lokeshdhakar.com/projects/lightbox2/">Lightbox 2</a> script, but that is for another day.</p>
<p>The reason I like the Facebox script is because you can also have inline content and content loaded via an AJAX call.</p>
<h2>Tweaking the Flickr Markup</h2>
<p>Since I do not want to modify the flickrRSS plugin to change the markup, I will just use jQuery to change the markup on body load.</p>
<p>So there are two things that I want to do:</p>
<ul>
<li>Add <code>rel="lightbox"</code> to each link containing the Flickr photo</li>
<li>Change the <code>href</code> to link to the <strong>medium image</strong> instead of linking to the Flickr page</li>
</ul>
<h3>The Code</h3>
<p>First, let&rsquo;s add the <code>rel="lightbox"</code> attribute to each of the links that are descendants of <code>ul#flickr</code> on body load:</p>
<pre><code>$(document).ready(function() {
	$('ul#flickr a').each(function() {
		$(this).attr('rel','lightbox');
	});
});</code></pre>
<p>Next, let&rsquo;s change the link to be the medium photo. We will do this by copying the source of the image, and then replacing <strong>_s.jpg</strong> with <strong>.jpg</strong>:</p>
<pre><code>$(document).ready(function() {
	$('ul#flickr a').each(function() {
		$(this).attr('rel','lightbox');
		var imgSrc = $(this).children().attr('src');
		$(this).attr('href',imgSrc.replace('_s.jpg','.jpg'))
	});
});</code></pre>
<p>Next, we just initiate the lightbox script by targeting links that have a rel attribute of <strong>lightbox</strong>:</p>
<pre><code>$(document).ready(function() {
	$('ul#flickr a').each(function() {
		$(this).attr('rel','lightbox');
		var imgSrc = $(this).children().attr('src');
		$(this).attr('href',imgSrc.replace('_s.jpg','.jpg'))
	});

	$('a[rel*=lightbox]').facebox();
});</code></pre>
<p>I have <a href="http://trevordavis.net/play/wordpress-flickr-plugin/enhancing-the-plugin-with-jquery/">modified the first demo page</a> to show this new functionality (although you can just look at <a href="http://trevordavis.net/#flickr">my footer</a> too).</p>
<p>It&rsquo;s pretty cool how just a few lines of jQuery can drastically improve the user experience.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/improving-a-flickr-plugin-with-jquery/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>Input vs. Button</title>
		<link>http://trevordavis.net/blog/tutorial/input-vs-button/</link>
		<comments>http://trevordavis.net/blog/tutorial/input-vs-button/#comments</comments>
		<pubDate>Wed, 21 May 2008 22:14:13 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=211</guid>
		<description><![CDATA[My latest redesign project at work was for Group Logic. Another company did the design and created static HTML templates. My role was to create a single header and footer to make maintaining the site easier, and to wrap the store and other dynamic applications in the new design.
The company who designed it used images [...]]]></description>
			<content:encoded><![CDATA[<p>My latest redesign project at work was for <a href="http://www.grouplogic.com/">Group Logic</a>. Another company did the design and created static HTML templates. My role was to create a single header and footer to make maintaining the site easier, and to wrap the store and other dynamic applications in the new design.</p>
<p>The company who designed it used images for the form buttons, and I found some interesting things while implementing them.</p>
<p><span id="more-211"></span></p>
<h2>A Disclaimer</h2>
<p>I think before you design form buttons to be images, you should seriously consider just styling the buttons with CSS. Just think about all of the images you will have to maintain. Is the value of the image button style really that great that you will deal with all of that hassle? In my opinion, it&rsquo;s not. But whatever, to each <strong>his</strong> own (you like that <a href="http://monadology.net/">Nate</a>?). Ok, enough with the disclaimer, now on to the good stuff.</p>
<h2>Some Options</h2>
<p>Ok, so I decided that there were 3 options for implementing these buttons:</p>
<ol>
<li>Use <code>&lt;input type="submit" /&gt;</code> and use an image replacement technique (that I didn&rsquo;t think would work in Safari).</li>
<li>Use <code>&lt;input type="image" /&gt;</code> and have the image source as an attribute.</li>
<li>Use <code>&lt;button type="submit"&gt;&lt;/button&gt;</code> and insert the image within the button element. </li>
</ol>
<h3>My Decision</h3>
<p>With ease of implementation in mind (since the time line was short), I decided to go with option 2: <code>&lt;input type="image" /&gt;</code>. Everything went fine until we decided to test in IE (6 and 7). Apparently, the value from the button does not get passed onto the server. After some Googling around, I found out that this is a well known problem, and the only way to get this to work is by using JavaScript. Whenever I code something with JavaScript, I want to make sure that it works without JavaScript. So that solution would not work.</p>
<h3>The Next Option</h3>
<p>Next, I went with option 3: <code>&lt;button type="submit"&gt;&lt;/button&gt;</code>. I really did not know much about the <code>button</code> element until I read <a href="http://particletree.com/features/rediscovering-the-button-element/">Rediscovering the Button Element</a> a year ago.</p>
<p>Again, that option worked fine in everything, except IE6 this time (in IE7, it passed in the entire source of the image as the value, but we could find a way to make that work). Apparently, if you have multiple button elements with the same name attributes, the value that comes out from the server in IE6 is the value from the last element on the form.</p>
<p>Ok, maybe that was confusing. The <a href="http://trevordavis.net/play/input-vs-button/">example page</a> might clarify some. The first example is just <code>&lt;input type="submit" /&gt;</code>. The second example is <code>&lt;input type="image" /&gt;</code>. Finally, the third example is <code>&lt;button type="submit"&gt;&lt;/button&gt;</code>.</p>
<p>Be sure to try that in IE6 and IE7 to see the problems I explained.</p>
<h3>A Third Try?</h3>
<p>Ok, this sucks, obviously I went with option 1 this time: <code>&lt;input type="submit" /&gt;</code>. We know from the <a href="http://trevordavis.net/play/input-vs-button/">first example on the previous page</a> that the value is at least passed through to the server properly in all browsers. Now the fun part is just trying to style the buttons in all browsers.</p>
<h2>Stying the Input Element</h2>
<p>Let&rsquo;s assign a class to all of the buttons we are going to style, and just add some basic styles to the button:</p>
<pre><code>input.buttons {
	background: none no-repeat top left;
	border: none;
	cursor: pointer;
	display: block;
	height: 25px;
	overflow: hidden;
	padding: 0;
	margin: 0 2px 0 0;
	text-indent: -9999px;
	width: auto;
}</code></pre>
<p>Most of that should be pretty self explanatory. So let&rsquo;s now add in the background images for the 3 buttons and give them a width:</p>
<pre><code>input.updateCart { background-image: url(update-cart.gif); width: 107px; }
input.continueShopping { background-image: url(continue-shopping.gif); width: 146px; }
input.proceedCheckout { background-image: url(proceed-to-checkout.gif); width: 156px; }</code></pre>
<p>The images are actually CSS Sprites so let&rsquo;s add in the hover effect:</p>
<pre><code>input.buttons:hover { background-position: 0 -25px; }</code></pre>
<p>Sweet, let&rsquo;s <a href="http://trevordavis.net/play/input-vs-button/regular-input/">take a look at the page</a>. Nice, it even looks good in Safari. Of course, it&rsquo;s broken in IE 6 and IE 7.</p>
<p><img src="http://trevordavis.net/wp-content/uploads/2008/05/buttons-ie.gif" alt="Strange effect on buttons in IE" class="imageCenter" height="25" width="413" /><em>Check out the weird buttons in IE</em></p>
<h3>Fixing for IE</h3>
<p>Ok, so I had no idea how to even attack this problem. So I started playing around, and finally came up with this:</p>
<pre><code>input.buttons { font-size: 0; line-height: 25px; }</code></pre>
<p>So I just serve those properties to IE6 and IE7. Beautiful, <a href="http://trevordavis.net/play/input-vs-button/regular-input-fixed-for-ie/">it works now</a>.</p>
<h3>One Last Thing</h3>
<p>So we were able to get these buttons working in all browsers. There is just one minor thing that bugged me. The hover effect does not work on the buttons in IE6. How about we use <a href="http://jquery.com/">jQuery</a> to fix that for IE6:</p>
<pre><code>$(document).ready(function(){
	$('input.buttons').hover(function() {
			$(this).css('background-position','0 -25px');
		},
		function() {
			$(this).css('background-position','0 0');
		}
	);
});</code></pre>
<p>Nice, <a href="http://trevordavis.net/play/input-vs-button/regular-input-hover-fixed-for-ie/">it works in IE6</a>. So yeah, that was really long. But form buttons are always a fun topic to get working across all browsers. Anyone have anything they would do differently?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/input-vs-button/feed/</wfw:commentRss>
		<slash:comments>56</slash:comments>
		</item>
		<item>
		<title>Set a Body Id Using PHP</title>
		<link>http://trevordavis.net/blog/tutorial/set-a-body-id/</link>
		<comments>http://trevordavis.net/blog/tutorial/set-a-body-id/#comments</comments>
		<pubDate>Thu, 08 May 2008 04:08:45 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=195</guid>
		<description><![CDATA[One of the first things I do when I am creating the markup for a new site, is to set a body id. You may wonder what I mean when I say &#8220;set a body id&#8221;. What I mean is to dynamically check the url to figure out which section you are in. This tutorial [...]]]></description>
			<content:encoded><![CDATA[<p>One of the first things I do when I am creating the markup for a new site, is to set a body id. You may wonder what I mean when I say &ldquo;set a body id&rdquo;. What I mean is to dynamically check the url to figure out which section you are in. This tutorial will show how to do this dynamically using PHP, and also how to integrate it into WordPress.</p>
<p><span id="more-195"></span></p>
<h2>Why Should I Set a Body Id?</h2>
<p>There are plenty of reasons why you should, here are a few:</p>
<ul>
<li>Maybe your design has different colors depending upon which section you are in. Instead of having to touch the markup, you can just modify the CSS depending upon the id on the <code>body</code>.</li>
<li>You can control the current states for your navigation.</li>
<li>Maybe the markup on your homepage is a little different than subpages, so instead of creating a different template, just stick in an if statement.</li>
</ul>
<h2>Setting Up the Code</h2>
<p>So typically, you setup your navigation to match your directory structure. Ex: Top level navigation is <strong>about</strong>, and there is a folder on the root called <strong>about</strong>. So the easiest thing to do, is just check the url and determine which section you are in. This is the code that sets the body id on my site:</p>
<pre><code>&lt;?php
function setBodyId() {
    $path = $_SERVER['REQUEST_URI'];

    if(!isset($bodyId)) {
		if(eregi('^/about/',$path) == 1) {
			$bodyId = 'about';
		} else if(eregi('^/blog/',$path) == 1) {
			$bodyId = 'blog';
		} else if(eregi('^/contact/',$path) == 1) {
			$bodyId = 'contact';
		} else if(eregi('^/work/',$path) == 1) {
			$bodyId = 'work';
		} else if(eregi('^/play/',$path) == 1) {
			$bodyId = 'play';
		} else if ($path == '') {
			$bodyId = 'home';
		} else {
			$bodyId = 'general';
		}
	}

    return $bodyId;
}
?></code></pre>
<p>Sure, you could do this dynamically and pull in the top level folder from the url, but I have found there are too many situations that arise where you want multiple sections to have the same body id, or you want to set other variables section by section. So I stick with this method, and it has been successful.</p>
<h2>My Example</h2>
<p>My example is going to be a little different because it is in a subsection of my site. So here is the code I am using to control setting the body id in the example:</p>
<pre><code>&lt;?php
function exampleSetBodyId() {
    $path = $_SERVER['REQUEST_URI'];

    if(!isset($bodyId)) {
		if(eregi('^/play/set-a-body-id/about/',$path) == 1) {
			$bodyId = 'about';
		} else if(eregi('^/play/set-a-body-id/blog/',$path) == 1) {
			$bodyId = 'blog';
		} else if(eregi('^/play/set-a-body-id/contact/',$path) == 1) {
			$bodyId = 'contact';
		} else if(eregi('^/play/set-a-body-id/work/',$path) == 1) {
			$bodyId = 'work';
		} else if(eregi('^/play/set-a-body-id/play/',$path) == 1) {
			$bodyId = 'play';
		} else if ($path == '/play/set-a-body-id/') {
			$bodyId = 'home';
		} else {
			$bodyId = 'general';
		}
	}

    return $bodyId;
}
$bodyId = exampleSetBodyId();
?&gt;</code></pre>
<p>So in the <code>$bodyId</code> variable, you have the value of the body id, so just print the variable on the <code>body</code> tag:</p>
<pre><code>&lt;body id="&lt;?=$bodyId; ?&gt;"&gt;</code></pre>
<h3>Some Practical Uses</h3>
<p>As I discussed at the beginning of the post, there are a lot of benefits to having a body id set on every page. This is the <a href="http://trevordavis.net/play/set-a-body-id/">demo section</a> that I am discussing below.</p>
<h4>Different Colors Per Section</h4>
<p>If you click through the navigation in the example, you can see the colors are different for each section. This can be easily accomplished without changing any markup through the power of <strong>descendant selectors.</strong> Here is the part of the CSS that is controlling the color of the borders:</p>
<pre><code>div#content { border: 1px solid #000; }
ul#nav { border-top: 1px solid #000; }
body#home div#content, body#home ul#nav { border-color: #FF6600; }
body#about div#content, body#about ul#nav { border-color: #429C19; }
body#blog div#content, body#blog ul#nav { border-color: #54D0ED; }
body#work div#content, body#work ul#nav { border-color: #A81919; }
body#play div#content, body#play ul#nav { border-color: #400152; }
body#contact div#content, body#contact ul#nav { border-color: #F8DC0C; }</code></pre>
<p>Here is the part that is changing the color of the <code>h1</code>:</p>
<pre><code>body#home h1 { color: #FF6600; }
body#about h1, { color: #429C19; }
body#blog h1 { color: #54D0ED; }
body#work h1 { color: #A81919; }
body#play h1 { color: #400152; }
body#contact h1 { color: #F8DC0C; }</pre>
<p></code></p>
<p>Obviously this is not the most beautiful example, but hopefully the idea makes sense.</p>
<h4>Current State on Navigation</h4>
<p>There are different ways to set the current state on the navigation, but by assigning an id to each navigation element, you can use descendant selectors again. Here is the markup:</p>
<pre><code>&lt;ul id="nav">
	&lt;li id="homeNav">&lt;a href="/play/set-a-body-id/">Home&lt;/a>&lt;/li>
	&lt;li id="aboutNav">&lt;a href="/play/set-a-body-id/about/">About&lt;/a>&lt;/li>
	&lt;li id="blogNav">&lt;a href="/play/set-a-body-id/blog/">Blog&lt;/a>&lt;/li>
	&lt;li id="workNav">&lt;a href="/play/set-a-body-id/work/">Work&lt;/a>&lt;/li>
	&lt;li id="playNav">&lt;a href="/play/set-a-body-id/play/">Play&lt;/a>&lt;/li>
	&lt;li id="contactNav">&lt;a href="/play/set-a-body-id/contact/">Contact&lt;/a>&lt;/li>
&lt;/ul></code></pre>
<p>Then, we use the following CSS to change the background color and text color when we are in that section:</p>
<pre><code>body#home ul#nav li#homeNav a { background: #FF6600; }
body#about ul#nav li#aboutNav a { background: #429C19; }
body#blog ul#nav li#blogNav a { background: #54D0ED; }
body#work ul#nav li#workNav a { background: #A81919; }
body#play ul#nav li#playNav a { background: #400152; }
body#contact ul#nav li#contactNav a { background: #F8DC0C; }
body#home ul#nav li#homeNav a, body#about ul#nav li#aboutNav a, body#blog ul#nav li#blogNav a, body#contact ul#nav li#contactNav a { color: #000; }
body#work ul#nav li#workNav a, body#play ul#nav li#playNav a { color: #fff; }</code></pre>
<h4>Slightly Different Homepage Markup</h4>
<p>Typically the markup for homepages are slightly different. But, if you are using one header and footer template for the entire site, you probably don&rsquo;t want to create another template just for the homepage. So since we have the body id that tells us when we are on the homepage, we can just write a simple <code>if</code> statement:</p>
<pre><code>&lt;?php if($bodyId == 'home') { ?&gt;
	&hellip;PUT YOUR HOMEPAGE SPECIFIC ELEMENTS HERE&hellip;
&lt;?php } ?&gt;</code></pre>
<h2>Make it Work with WordPress</h2>
<p>So just take the <strong>setBodyId function</strong> that we defined earlier, and add it to your WordPress theme functions (functions.php).</p>
<p>After you have added the function, we want to add actions to <a href="http://codex.wordpress.org/Hook_Reference/wp_head">wp_head</a> and <strong>wp_footer</strong> (for some reason there isn&rsquo;t a WordPress Hook Reference for wp_footer, but it is essentially the same as wp_head, just in the footer). Here is how we add our function to those hooks:</p>
<pre><code>add_action('wp_head', 'setBodyId');
add_action('wp_footer', 'setBodyId');</code></pre>
<p>Then, in your header, just call the <strong>wp_head</strong> hook, and call our function:</p>
<pre><code>&lt;?php wp_head(); $bodyId = setBodyId(); ?&gt;</code></pre>
<p>There you have it, you have the body id defined in the <code>$bodyId</code> variable, and you can do with it what you want.</p>
<h2>Other Thoughts</h2>
<p>I think by setting an id (or class) on such a high level element gives you a lot of control over its descendants. Another interesting idea that I heard was to use <a href="http://jquery.com/">jQuery</a> to determine the browser and version that the user is using, then add a class on the body. That way you could differ your CSS depending on which class is on the <code>body</code>. That idea would eliminate the need for conditional comments (at least for users with JavaScript enabled).</p>
<p>So hopefully this tutorial shows you an easy way to make some site-wide tasks simpler, and I am interested to see if other people have ideas for what to do with body ids.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/set-a-body-id/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Handling WordPress Trackbacks with jQuery</title>
		<link>http://trevordavis.net/blog/tutorial/handling-wordpress-trackbacks-with-jquery/</link>
		<comments>http://trevordavis.net/blog/tutorial/handling-wordpress-trackbacks-with-jquery/#comments</comments>
		<pubDate>Tue, 15 Apr 2008 01:54:32 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=185</guid>
		<description><![CDATA[So after having a ton of trackbacks in a recent article, The 6 Most Important CSS Techniques You Need To Know, I thought that it was kind of breaking up the flow of the comments.
I didn&#8217;t necessarily want to completely remove them because I thought that some people might be interested in them. These are [...]]]></description>
			<content:encoded><![CDATA[<p>So after having a ton of trackbacks in a recent article, <a href="http://trevordavis.net/blog/tutorial/the-6-most-important-css-techniques-you-need-to-know/">The 6 Most Important CSS Techniques You Need To Know</a>, I thought that it was kind of breaking up the flow of the comments.</p>
<p>I didn&rsquo;t necessarily want to completely remove them because I thought that some people might be interested in them. These are the steps that I want to take:</p>
<ol>
<li>Assign a class to all trackbacks</li>
<li>Hide them all with CSS</li>
<li>Add a jQuery visibility toggle</li>
</ol>
<p><span id="more-185"></span></p>
<h2>1) Assign a Class to All Trackbacks</h2>
<p>In your <strong>comments.php</strong> theme file, find a line that looks like this:</p>
<pre><code>&lt;li id="comment-&lt;?php comment_ID() ?>"></code></pre>
<p>And replace it with this:</p>
<pre><code>&lt;li class="&lt;?php if(get_comment_type() != 'comment') echo 'trackback'; ?>" id="comment-&lt;?php comment_ID() ?>"></code></pre>
<h3>Explanation</h3>
<p>The get_comment_type function returns either <strong>comment</strong>, <strong>trackback</strong>, or <strong>pingback</strong>. Since I want to hide everything except comments, I filter out anything that <strong>does not equal comment</strong>, so I assign a class of trackback to that list item.</p>
<h2>2) Hide them All with CSS</h2>
<p>Ok, easy enough, just add the following to your stylesheet:</p>
<pre><code>ol.commentlist li.trackback { display: none; }</code></pre>
<p>That should be pretty self explanatory.</p>
<h2>3) Add a jQuery Visibility Toggle</h2>
<p>The logic of the JavaScript will be as follows:</p>
<ol>
<li>Check to see if there are any list items with a class of trackback.</li>
<li>Add a link to Show/Hide trackbacks.</li>
<li>Add a click event to the Show/Hide trackback link.</li>
<li>Update the text of the link accordingly.</li>
</ol>
<p>First, let&rsquo;s execute the JavaScript once the document is ready:</p>
<pre><code>$(document).ready(function(){

});</code></pre>
<p>Next, let&rsquo;s check to see if there are any elements with a class of trackback:</p>
<pre><code>$(document).ready(function(){
	if($('.trackback').length > 0) {

	}
});</code></pre>
<p>Next, if there are trackbacks on the page, insert a link to show trackbacks:</p>
<pre><code>$(document).ready(function(){
	if($('.trackback').length > 0) {
		$('#comments').after('&lt;a href="#" id="toggleTrackbacks">(Show Trackbacks)&lt;/a>');
	}
});</code></pre>
<p>I am adding the show/hide trackback link after the heading with an id of <strong>comments</strong>.</p>
<p>Finally, I want to add in the <strong>click</strong> event to the link, and toggle the text depending upon if the trackbacks are visible or not:</p>
<pre><code>$(document).ready(function(){
	if($('.trackback').length > 0) {
		$('#comments').after('&lt;a href="#" id="toggleTrackbacks">(Show Trackbacks)&lt;/a>');
		$('#toggleTrackbacks').click(function() {
			$('.trackback').slideToggle('slow');
			if($('#toggleTrackbacks').text() == '(Show Trackbacks)') {
				$('#toggleTrackbacks').text('(Hide Trackbacks)');
			} else {
				$('#toggleTrackbacks').text('(Show Trackbacks)');
			}
			return false;
		});
	}
});</code></pre>
<p>So basically, I am adding the jQuery <strong>slideToggle</strong> effect when the show/hide trackbacks link is clicked. Then, if the text in the show/hide trackbacks link is <strong>Show Trackbacks</strong>, I change it to <strong>Hide Trackbacks</strong>, and the opposite when the text is Hide Trackbacks.</p>
<p>I have grabbed some of the comments from <a href="http://trevordavis.net/blog/tutorial/the-ultimate-png-guide/">The Ultimate PNG Guide</a> so you can <a href="http://trevordavis.net/play/jquery-collapse-trackbacks/">see a demo of this in action</a>.</p>
<p>I love how simple jQuery is.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/handling-wordpress-trackbacks-with-jquery/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The 6 Most Important CSS Techniques You Need To Know</title>
		<link>http://trevordavis.net/blog/tutorial/the-6-most-important-css-techniques-you-need-to-know/</link>
		<comments>http://trevordavis.net/blog/tutorial/the-6-most-important-css-techniques-you-need-to-know/#comments</comments>
		<pubDate>Mon, 31 Mar 2008 02:40:06 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=169</guid>
		<description><![CDATA[I thought I would give a quick tutorial, with examples, of the 6 most important CSS techniques that I think you need to know:

Get a Consistent Base Font Size
Get Consistent Margins
Set a Float to Clear a Float
Image Replacement
Faux Columns
CSS Sprites


1. Get a Consistent Base Font Size
body { font-size: 62.5%; }
Until IE finally supports the resizing [...]]]></description>
			<content:encoded><![CDATA[<p>I thought I would give a quick tutorial, with examples, of the 6 most important CSS techniques that I think you need to know:</p>
<ol>
<li>Get a Consistent Base Font Size</li>
<li>Get Consistent Margins</li>
<li>Set a Float to Clear a Float</li>
<li>Image Replacement</li>
<li>Faux Columns</li>
<li>CSS Sprites</li>
</ol>
<p><span id="more-169"></span></p>
<h2 class="replaceHeadline">1. Get a Consistent Base Font Size</h2>
<pre><code>body { font-size: 62.5%; }</code></pre>
<p>Until IE finally supports the resizing of text in pixels, this is the best technique to gain full control over your font sizes. By setting the body <code>font-size</code> to 62.5%, that will set your font size to 10 pixels. That way, 1em is equal to 10 pixels.</p>
<p>Although I typically then set my container <code>font-size</code> to 1.2em, which in turn sets the <code>font-size</code> to 12 pixels. But still, then you know that 1em is equal to 12 pixels.</p>
<p><a href="http://trevordavis.net/play/important-css-techniques/base-font-size/">See the example &raquo;</a></p>
<h2 class="replaceHeadline">2. Get Consistent Margins</h2>
<p>There are <a href="http://meyerweb.com/eric/tools/css/reset/">some great CSS resets</a> out there, but I usually don&rsquo;t need one that goes so far. I like to just remove the margin and padding from every element.</p>
<pre><code>html, body, div, h1, h2, h3, h4, h5, h6, ul, ol, dl, li, dt, dd, p, blockquote, pre, form, fieldset, table, th, td { margin: 0; padding: 0; }</code></pre>
<p>Then, you can set the margins that you want accordingly.</p>
<p><a href="http://trevordavis.net/play/important-css-techniques/get-consistent-margins/">See the example &raquo;</a></p>
<h2 class="replaceHeadline">3. Set a Float to Clear a Float</h2>
<p>Floating is probably one of the most important things to understand with CSS, but knowing how to clear floats is necessary too. All you need to remember is: <strong>Set a Float to Clear a Float</strong>.</p>
<p>I have created a <a href="http://trevordavis.net/play/important-css-techniques/set-a-float-to-clear-a-float/">simple page with two floating columns next to each other</a>. You will notice in the example that the grey background does not contain the floating columns. So, the easiest thing to do is to <a href="http://trevordavis.net/play/important-css-techniques/set-a-float-to-clear-a-float/set-a-float-to-clear-a-float-fixed/">set the containing element to float</a>. But now, you will see that the container background doesn&rsquo;t contain the content area.</p>
<p>Since the container has <code>margin: 0 auto</code>, we do not want to float it because it will move it to whichever side we float it. So another way to clear the float, is to <a href="http://trevordavis.net/play/important-css-techniques/set-a-float-to-clear-a-float/set-a-float-to-clear-a-float-fixed-more/">insert a clearing element</a>. In this case, I just use an empty <code>div</code> set to <code>clear: both</code>. Now, there are other ways to <a href="http://www.positioniseverything.net/easyclearing.html">clear a float without markup</a>, but I have noticed some inconsistencies with that technique, so I just sacrifice an empty <code>div</code>.</p>
<h2 class="replaceHeadline">4. Image Replacement</h2>
<p>Sure, <a href="http://www.mezzoblue.com/tests/revised-image-replacement/">there are a lot of different image replacement techniques</a>. But, I think that you get to most benefits from this technique. I also discussed this technique in a previous article, <a href="http://trevordavis.net/blog/tutorial/improved-navigation-image-replacement/">Improved Navigation Image Replacement</a></p>
<h3 class="replaceHeadline">The Markup</h3>
<pre><code>&lt;h1 id="logo">Company Name&lt;span>&lt;/span>&lt;/h1></code></pre>
<h3 class="replaceHeadline">The CSS</h3>
<pre><code>h1#logo {
	height: 110px;
	overflow: hidden;
	position: relative;
	width: 560px;
}
h1#logo span {
	background: url(/wp-content/uploads/2008/03/logo.gif) no-repeat;
	display: block;
	height: 100%;
	left: 0;
	position: absolute;
	top: 0;
	width: 100%;
}</code></pre>
<p>Basically, all we are doing is absolutely positioning an image over top of the HTML text.</p>
<p>The reason that I like this technique is because even when images are disabled, the text is still visible. Of course this means that you cannot use a transparent image to lay over top of the text, so it will not work in all situations.</p>
<p><a href="http://trevordavis.net/play/important-css-techniques/image-replacement/">See the example &raquo;</a></p>
<h2 class="replaceHeadline">5. Faux Columns</h2>
<p>It is very common in layouts to have 2 columns next to each other, with one column having a background color, and the other column just being white. Since the columns will almost never have the same amount of content in them, the easiest way to fake this, is to have a <strong>1px tall background image</strong> being repeated vertically in the containing element of the 2 columns.</p>
<h3 class="replaceHeadline">The Markup</h3>
<pre><code>&lt;div id="container">
	&lt;div id="primaryContent">
		&lt;h1>Primary Column&lt;/h1>
		&lt;p>&hellip;&lt;/p>
	&lt;/div>
	&lt;div id="secondaryContent">
		&lt;h2>Secondary Column&lt;/h2>
		&lt;p>&hellip;&lt;/p>
	&lt;/div>
	&lt;div class="clearing">&lt;/div>
&lt;/div></code></pre>
<h3 class="replaceHeadline">The CSS</h3>
<pre><code>div#container {
	background: url(/wp-content/uploads/2008/03/content-bg.gif) repeat-y top right;
	padding: 10px 0;
	width: 640px;
}
div#primaryContent { float: left; padding: 0 10px; width: 400px; }
div#secondaryContent { float: right; padding: 0 10px; width: 200px; }</code></pre>
<p>Pretty simple: a containing element, 2 floating columns, and a clearing element so that the containing element will contain the floating columns (as noted in the <strong>Set a Float to Clear a Float</strong> technique above).</p>
<p><a href="http://trevordavis.net/play/important-css-techniques/faux-columns/">See the example &raquo;</a></p>
<h2 id="cssSprites">6. CSS Sprites</h2>
<p>CSS sprites is the technique of combing images to lessen the number of calls that need to be made to the server. Then you just shift the position of the background image to view the correct part of the image. May sound complicated, but it just takes a little math. <em>Note: In both of these examples, I am using the <strong>Image Replacement</strong> technique discussed above.</em></p>
<h3 class="replaceHeadline">Example #1</h3>
<p>For this example, we are just going to have one download link that we want to replace with a nice graphic. Then, on hover, we want to change the image.</p>
<h4 class="replaceHeadline">The Markup</h4>
<pre><code>&lt;a href="#" id="download">Download Now&lt;span>&lt;/span>&lt;/a></code></pre>
<h4 class="replaceHeadline">The CSS</h4>
<pre><code>a#download {
	display: block;
	height: 75px;
	overflow: hidden;
	position: relative;
	width: 150px;
}
a#download span {
	background: url(/wp-content/uploads/2008/03/download.gif) no-repeat;
	display: block;
	height: 100%;
	left: 0;
	position: absolute;
	top: 0;
	width: 100%;
}
a#download:hover span { background-position: 0 -75px; }</code></pre>
<p>As you can see from the code, on hover, we shift the position of the background image to view a different part of the image.</p>
<p>Oh, and also, IE6 and 7 suck, so here are the styles we are serving to them:</p>
<h5 class="replaceHeadline">Styles to IE6 and IE7</h5>
<pre><code>a#download { cursor: pointer; }</code></pre>
<p>I realize that we could just put that in the regular stylesheet since it has no affect on other browsers, but I prefer to move stuff like that to the IE only stylesheets.</p>
<h5 class="replaceHeadline">Styles to IE6 Only</h5>
<pre><code>a#download:hover { background-position: 0 0; }</code></pre>
<p>This is some weird bug where the images shift when you hover, but then when you mouse-out, the images don&rsquo;t shift back.</p>
<p><a href="http://trevordavis.net/play/important-css-techniques/css-sprites/">See the example &raquo;</a></p>
<h3 class="replaceHeadline">Example #2</h3>
<p>For the second example, we are going to use the CSS sprites technique, but for the entire navigation. This way, only one call needs to be made to the server to load the navigation. We are basically creating a CSS sprites matrix.</p>
<h4 class="replaceHeadline">The Markup</h4>
<pre><code>&lt;ul id="nav">
	&lt;li id="home">&lt;a href="#">Home&lt;span>&lt;/span>&lt;/a>&lt;/li>
	&lt;li id="about">&lt;a href="#">About&lt;span>&lt;/span>&lt;/a>&lt;/li>
	&lt;li id="work">&lt;a href="#">Work&lt;span>&lt;/span>&lt;/a>&lt;/li>
	&lt;li id="play">&lt;a href="#">Play&lt;span>&lt;/span>&lt;/a>&lt;/li>
	&lt;li id="contact">&lt;a href="#">Contact&lt;span>&lt;/span>&lt;/a>&lt;/li>
&lt;/ul></code></pre>
<h4 class="replaceHeadline">The CSS</h4>
<pre><code>ul#nav { background: #91c6d5; float:left; list-style: none; width: 510px; }
ul#nav li { float: left; }
ul#nav a { color: #000; display: block; font-size: 1.5em; height: 38px; text-align: center; position: relative; }
ul#nav span { background: url(/wp-content/uploads/2008/03/nav.gif) no-repeat; display: block; height: 100%; left: 0; position: absolute; top: 0; width: 100%; }

ul#nav li#home a { width: 102px; }
ul#nav li#home a:hover span { background-position: 0 -38px; }

ul#nav li#about a { width: 106px; }
ul#nav li#about span { background-position: -102px 0; }
ul#nav li#about a:hover span { background-position: -102px -38px; }

ul#nav li#work a { width: 92px; }
ul#nav li#work span { background-position: -208px 0; }
ul#nav li#work a:hover span { background-position: -208px -38px; }

ul#nav li#play a { width: 79px; }
ul#nav li#play span { background-position: -300px 0; }
ul#nav li#play a:hover span { background-position: -300px -38px; }

ul#nav li#contact a { width: 131px; }
ul#nav li#contact span { background-position: -379px 0; }
ul#nav li#contact a:hover span { background-position: -379px -38px; }
</code></pre>
<p>That may seem crazy, but it all makes sense if you take the time to think about it.</p>
<p>Again, we have to serve some similar styles to IE6 and 7 from the previous example:</p>
<h5 class="replaceHeadline">Styles to IE6 and IE7</h5>
<pre><code>ul#nav a { cursor: pointer; }</code></pre>
<h5 class="replaceHeadline">Styles to IE6 Only</h5>
<pre><code>ul#nav a:hover { background-position: 0 0; }</code></pre>
<p><a href="http://trevordavis.net/play/important-css-techniques/css-sprites/">See the example &raquo;</a></p>
<h2 class="replaceHeadline">In Conclusion</h2>
<p>This list is definitely not exhaustive; they are just the 6 that I think are extremely important. <strong>What other techniques do you think are important to know?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/the-6-most-important-css-techniques-you-need-to-know/feed/</wfw:commentRss>
		<slash:comments>147</slash:comments>
		</item>
		<item>
		<title>Use jQuery to Open All External Links in a New Window</title>
		<link>http://trevordavis.net/blog/tutorial/use-jquery-to-open-all-external-links-in-a-new-window/</link>
		<comments>http://trevordavis.net/blog/tutorial/use-jquery-to-open-all-external-links-in-a-new-window/#comments</comments>
		<pubDate>Wed, 12 Mar 2008 02:11:39 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/blog/tutorial/use-jquery-to-open-all-external-links-in-a-new-window/</guid>
		<description><![CDATA[In a recent project at work, I had completed implementing a site, and the client was reviewing it. Their company decided that they wanted all external links to open in a new window. This is not a practice that I really like, and others agree:

Opening up new browser windows is like a vacuum cleaner sales [...]]]></description>
			<content:encoded><![CDATA[<p>In a recent project at work, I had completed implementing a site, and the client was reviewing it. Their company decided that they wanted all external links to open in a new window. This is not a practice that I really like, and others agree:</p>
<blockquote>
<p>Opening up new browser windows is like a vacuum cleaner sales person who starts a visit by emptying an ash tray on the customer&#8217;s carpet. Don&#8217;t pollute my screen with any more windows, thanks (particularly since current operating systems have miserable window management). If I want a new window, I will open it myself!</p>
<p><cite>Jakob Nielsen: <a href="http://www.useit.com/alertbox/990530.html">The Top Ten Web Design Mistakes of 1999</a></cite></p>
</blockquote>
<p>Breaking the back button is never a good thing. But this article is not about that.</p>
<p>Back to the site I was implementing. I was really not interested in adding <code>target="_blank"</code> to every single external link, so I came up with a better solution&hellip;</p>
<p><span id="more-162"></span></p>
<h2 class="replaceHeadline">The Solution</h2>
<p>The site was already using jQuery for other functions, so I figured that I should just use some of its powerfulness to make my life easier.</p>
<p>With a couple lines of code, I solved my problem:</p>
<pre><code>$(document).ready(function(){
	$("a[@href^='http']").attr('target','_blank');
});</code></pre>
<p><a href="http://trevordavis.net/play/jquery-open-external-links-in-new-window/">Check out the demo to see the results.</a></p>
<h3 class="replaceHeadline">Explanation</h3>
<p>If you know anything about <a href="http://trevordavis.net/blog/tutorial/css-attribute-selectors-explained/">attribute selectors</a>, that should look familiar to you. Basically, it is saying, apply the attribute <code>target="_blank"</code> to all links that begin with <strong>http</strong>.</p>
<p>Really easy, really powerful, problem solved. Some may say it almost might be preferable to browse the site with JavaScript disabled so that the external links would just open in the same window. But that debate is for another time.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/use-jquery-to-open-all-external-links-in-a-new-window/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>PNGs, the AlphaImageLoader Filter, and hasLayout</title>
		<link>http://trevordavis.net/blog/tutorial/pngs-the-alphaimageloader-filter-and-haslayout/</link>
		<comments>http://trevordavis.net/blog/tutorial/pngs-the-alphaimageloader-filter-and-haslayout/#comments</comments>
		<pubDate>Fri, 07 Mar 2008 03:25:02 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/blog/tutorial/pngs-the-alphaimageloader-filter-and-haslayout/</guid>
		<description><![CDATA[I recently wrote an article discussing how to use PNGs effectively in all browsers (including IE6). For work, I had to slice a site that used a lot of PNGs, and I ran into something that I had never encountered before.

I was trying to use the Microsoft proprietary AlphaImageLoader Filter because they background images were [...]]]></description>
			<content:encoded><![CDATA[<p>I recently wrote an article discussing <a href="http://trevordavis.net/blog/tutorial/the-ultimate-png-guide/">how to use PNGs effectively in all browsers (including IE6)</a>. For work, I had to slice a site that used a lot of PNGs, and I ran into something that I had never encountered before.</p>
<p><span id="more-160"></span></p>
<p>I was trying to use the Microsoft proprietary <a href="http://msdn2.microsoft.com/en-us/library/ms532969(VS.85).aspx">AlphaImageLoader Filter</a> because they background images were PNGs that were going to scale to fit the background. The <code>div</code> that I was setting the PNG as the background to, did not have a height or width specified. Apparently, to use the AlphaImageLoader property, the element that you are using it on must have another Microsoft propriety property: <a href="http://msdn2.microsoft.com/en-us/library/ms533776.aspx">hasLayout</a>.</p>
<p>From the Microsoft Developer Network Site:</p>
<blockquote><p>The object that the filter is applied to must have layout before the filter effect will display. You can give the object layout by setting the <strong>height</strong> or <strong>width</strong> property, setting the position property to <strong>absolute</strong>.</p>
</blockquote>
<h2 class="replaceHeadline">An Example</h2>
<p>I am going to use <a href="http://trevordavis.net/play/pngs/example-4/">the same working example</a> I used in my <a href="http://trevordavis.net/blog/tutorial/the-ultimate-png-guide/">Ultimate PNG Guide</a>. But this time, I am going to add the following to the head of the page:</p>
<pre><code>&lt;style type="text/css">
div#container div.inner { width: auto; }
&lt;/style></code></pre>
<p>Obviously not how you would want to really add that style to the page, but I am just trying to prove that in IE6, to use a PNG with the AlphaImageLoader Filter applied, the element must <strong>have layout</strong>. <a href="http://trevordavis.net/play/pngs/pngs-and-haslayout/">So here is the new page, which should be broken in IE6.</a></p>
<p>So there you have it, remember to give elements <strong>layout</strong> if you are going to use the <strong>AlphaImageLoader Filter</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/pngs-the-alphaimageloader-filter-and-haslayout/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Get Age Function</title>
		<link>http://trevordavis.net/blog/tutorial/get-age-function/</link>
		<comments>http://trevordavis.net/blog/tutorial/get-age-function/#comments</comments>
		<pubDate>Wed, 06 Feb 2008 02:45:17 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/blog/tutorial/php-get-age-function/</guid>
		<description><![CDATA[Such things like copyright dates, ages, etc. can cause problems on websites unless they are dynamic. For example, I have my age in the little about me blurb in the sidebar. I made a little function to calculate my age so that I don&#8217;t have to go in every year on my birthday and add [...]]]></description>
			<content:encoded><![CDATA[<p>Such things like copyright dates, ages, etc. can cause problems on websites unless they are dynamic. For example, I have my age in the little about me blurb in the sidebar. I made a little function to calculate my age so that I don&rsquo;t have to go in every year on my birthday and add another year to my age.</p>
<p><span id="more-144"></span></p>
<h2 class="replaceHeadline">The Function</h2>
<pre><code>function age($bMonth,$bDay,$bYear) {

	$cMonth = date('n');
	$cDay = date('j');
	$cYear = date('Y');

	if(($cMonth >= $bMonth &#038;&#038; $cDay >= $bDay) || ($cMonth > $bMonth)) {
		return ($cYear - $bYear);
	} else {
		return ($cYear - $bYear - 1);
	}
}</code></pre>
<p>This function takes 3 arguments: the birth month, the birth day, and the birth year. It will return the calculated age. It obviously won&rsquo;t work with an age in the future; it will return a negative number. I could add in checking to see if it&rsquo;s a valid date, but I don&rsquo;t think it&rsquo;s really necessary.</p>
<p><a href="http://trevordavis.net/play/php-get-age-function-examples/">Check Out Some Examples</a></p>
<p>Nothing too complicated. Let me know if anyone has any suggestions to shorten the code.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/get-age-function/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Updated Dean Edwards&#8217; IE7 Scripts</title>
		<link>http://trevordavis.net/blog/tutorial/updated-dean-edwards-ie7-scripts/</link>
		<comments>http://trevordavis.net/blog/tutorial/updated-dean-edwards-ie7-scripts/#comments</comments>
		<pubDate>Wed, 09 Jan 2008 02:51:56 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=50</guid>
		<description><![CDATA[As I have noted in previous posts: Using Dean Edwards&#8217; IE7 Script, The Ultimate PNG Guide, I am a big advocate of the Dean Edwards&#8217; IE7 scripts.
Thankfully, Dean has improved them even more. Instead of having a ton of different JavaScript files with large file sizes, he has compressed them into two light-weight JavaScript files.

The [...]]]></description>
			<content:encoded><![CDATA[<p>As I have noted in previous posts: <a href="http://trevordavis.net/blog/tutorial/using-dean-edwards-ie7-script/">Using Dean Edwards&rsquo; IE7 Script</a>, <a href="http://trevordavis.net/blog/tutorial/the-ultimate-png-guide/">The Ultimate PNG Guide</a>, I am a big advocate of the Dean Edwards&rsquo; IE7 scripts.</p>
<p>Thankfully, <a href="http://dean.edwards.name/weblog/2008/01/ie7-2/">Dean has improved them even more</a>. Instead of having a ton of different JavaScript files with large file sizes, he has compressed them into two light-weight JavaScript files.</p>
<p><span id="more-50"></span></p>
<p>The are now two scripts, <a href="http://trevordavis.net/ie7/IE7.js">IE7.js</a> and <a href="http://trevordavis.net/ie7/IE8.js">IE8.js</a>, and they are <a href="http://code.google.com/p/ie7-js/">hosted on Google Code</a>. The IE7.js file &ldquo;fixes&rdquo; IE5 and IE6 so that it is up to par with IE7. Then, IE8.js adds in some additional functionality that is missing from IE7. <strong>Note:</strong> If you include IE8.js, you <strong>do not</strong> need to include IE7.js.</p>
<h2 class="replaceHeadline">Usage</h2>
<p>There are a couple of different options here, you can either download the files and place them on your server or link directly to the Google Code version.</p>
<h3 class="replaceHeadline">Option 1: Download Files</h3>
<ol>
<li><a href="http://ie7-js.googlecode.com/files/ie7-2.0%28beta%29.zip">Download the ZIP file</a>.</li>
<li>Extract the IE7 folder to the root of your server.</li>
<li>
<p>Include the script in the head of your document:</p>
<pre><code>&lt;!--[if lt IE 7]>
&lt;script src="/ie7/IE8.js" type="text/javascript">&lt;/script>
&lt;![endif]--></code></pre>
<p>In this example, I am targeting all versions of Internet Explorer less than IE7, and applying the IE8 script to it. Or, you could apply the IE7 script instead, I just wanted the advanced CSS functionality.</p>
<p>You could also set it so that it is applied in IE7 as well:</p>
<pre><code>&lt;!--[if lte IE 7]>
&lt;script src="/ie7/IE8.js" type="text/javascript">&lt;/script>
&lt;![endif]--></code></pre>
</li>
<li>Open IE6 and enjoy some things not being broken.</li>
</ol>
<h3 class="replaceHeadline">Option 2: Link to Google Code Files</h3>
<ol>
<li><a href="http://ie7-js.googlecode.com/svn/version/">Find the version of the file you want to use</a></li>
<li>Copy the URL, ex: <a href="http://ie7-js.googlecode.com/svn/version/2.0(beta)/IE8.js">http://ie7-js.googlecode.com/svn/version/2.0(beta)/IE8.js</a></li>
<li>
<p>Include the script in the head of your document:</p>
<pre><code>&lt;!--[if lt IE 7]>
&lt;script src="http://ie7-js.googlecode.com/svn/version/2.0(beta)/IE8.js" type="text/javascript">&lt;/script>
&lt;![endif]--></code></pre>
</li>
<li>Smile, you just &ldquo;fixed&rdquo; IE6.</li>
</ol>
<p>Hopefully that should get you started with what you need. My previous articles: <a href="http://trevordavis.net/blog/tutorial/using-dean-edwards-ie7-script.php">Using Dean Edwards&rsquo; IE7 Script</a>, <a href="http://trevordavis.net/blog/tutorial/the-ultimate-png-guide.php">The Ultimate PNG Guide</a> have some other details about the previous version of the script, some of which still apply.</p>
<p>Let me know if you have questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/updated-dean-edwards-ie7-scripts/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The Ultimate PNG Guide</title>
		<link>http://trevordavis.net/blog/tutorial/the-ultimate-png-guide/</link>
		<comments>http://trevordavis.net/blog/tutorial/the-ultimate-png-guide/#comments</comments>
		<pubDate>Wed, 26 Dec 2007 21:36:04 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=46</guid>
		<description><![CDATA[I would say one of the coolest things in web development/design is the creative use of PNGs. Although, it&#8217;s a little hard because of the way that IE6 handles them.
I have already written about Using Dean Edwards&#8217; IE7 Script, but I wanted to take it a step further and talk more about PNGs.

To Review

First, download [...]]]></description>
			<content:encoded><![CDATA[<p>I would say one of the coolest things in web development/design is the creative use of PNGs. Although, it&rsquo;s a little hard because of the way that IE6 handles them.</p>
<p>I have already written about <a href="http://trevordavis.net/blog/tutorial/using-dean-edwards-ie7-script/">Using Dean Edwards&rsquo; IE7 Script</a>, but I wanted to take it a step further and talk more about PNGs.</p>
<p><span id="more-46"></span></p>
<h2 class="replaceHeadline">To Review</h2>
<blockquote>
<p>First, <a href="http://dean.edwards.name/download/">download the Dean Edwards script</a>. Next, extract the files to the root of your webserver in a folder called <strong>ie7</strong>. It needs to be in this folder, because some of the scripts have a dependency on the folder.</p>
<p>Finally, just include the script in the head of your document using conditional comments:</p>
</blockquote>
<pre><code>&lt;!--[if lt IE 7]&gt;
&lt;script src="/ie7/ie7-standard-p.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;![endif]--&gt;</code></pre>
<p>Ok, so now when you want to have the script &ldquo;fix&rdquo; the PNG in IE6, you just have to have <strong>-trans.png</strong> as the suffix of the filename of the image.</p>
<h2 class="replaceHeadline">An Example</h2>
<p>Now, I am no designer, but I have <a href="http://trevordavis.net/wp-content/uploads/2008/01/png-screenshot.png">mocked-up a simple page to show some usage of PNGs</a>.</p>
<p>Since the background on the body is the repeated diagonal lines, we cannot use a GIF for the rounded corners, because we aren&rsquo;t sure where the corners will intersect with the lines on the bottom.</p>
<p>In an ideal world, <a href="http://trevordavis.net/play/pngs/">this is how I would want to mark the page up.</a></p>
<p>But, in IE6, the PNGs have a blue glow around them. So if we <a href="http://trevordavis.net/play/pngs/example-2/">apply the Dean Edwards scripts to the page</a>, we see the bottom image disappears (keep in mind you have to be looking in IE6 to see this problem). This is because the script is applying the IE proprietary filter property, and once this applied, we cannot position or repeat a PNG.</p>
<p><a href="http://trevordavis.net/play/pngs/example-3/">So let&rsquo;s change the way we are marking it up so that the bottom shows up in IE6</a>. Basically, we have just added an empty <code>div</code> that contains the bottom background PNG.</p>
<p>Now we just have to worry about the repeated background of our main content area. In order to get rid of the blue glow, we have to apply IE&rsquo;s filter property, which means that we can&#8217;t repeat it.</p>
<p>But, if we apply the filter property manually and change the sizingMethod to scale, <a href="http://trevordavis.net/play/pngs/example-4/">we can give the effect of repeating the background</a>.</p>
<pre><code>div#container div.inner {
	background-image: url(blank.gif);
	filter: progid:DXImageTransform.Microsoft.AlphaImageLoader (src='/wp-content/uploads/2008/01/container-bg.png', sizingMethod='scale');
}</code></pre>
<p>Basically, it&rsquo;s just stretching the image to fit the area, but since it&rsquo;s a simple image that we were going to repeat anyways, it looks fine stretched.</p>
<h3 class="replaceHeadline">In Conclusion</h3>
<p>Hopefully using a combination of these two PNG fixes can provide you with enough to get things looking good in all browsers.</p>
<p>Anyone have any other solutions?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/the-ultimate-png-guide/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Creating Multiple Sites on a Local Web Server</title>
		<link>http://trevordavis.net/blog/tutorial/creating-multiple-sites-on-a-local-web-server/</link>
		<comments>http://trevordavis.net/blog/tutorial/creating-multiple-sites-on-a-local-web-server/#comments</comments>
		<pubDate>Thu, 06 Dec 2007 03:24:55 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=43</guid>
		<description><![CDATA[So while I was redesigning my site, I needed somewhere to develop the new design. I didn&#8217;t want to have to setup a sub-domain on the live site because that would be a pain to have to FTP files up everytime I changed something. So I installed XAMPP on my computer.
Basically, XAMPP is a all [...]]]></description>
			<content:encoded><![CDATA[<p>So while I was redesigning my site, I needed somewhere to develop the new design. I didn&rsquo;t want to have to setup a sub-domain on the live site because that would be a pain to have to FTP files up everytime I changed something. So I installed <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a> on my computer.</p>
<p>Basically, XAMPP is a all in one Apache web server. It installs Apache, PHP, MySQL&hellip;everything I needed.</p>
<p><span id="more-43"></span></p>
<p>Once you install it, you get a web directory here <strong>C:\Program Files\xampp\htdocs</strong> (or whichever directory you install XAMPP to). That&rsquo;s great, everything works fine when you put things in that directory and browse to <strong>localhost</strong>. But what about if you want to setup multiple sites? That is where I really had to do some digging.</p>
<h2 class="replaceHeadline">Setting Up Multiple Sites</h2>
<p>I found this really good article that walks you through <a href="http://www.campbellssource.com/multiple-website-on-xampp/">setting up multiple sites on XAMPP</a>. The article was a little longer than I thought it had to be, so I thought I would clarify some things.</p>
<ol>
<li>Find this file: <strong>C:\Program Files\xampp\apache\conf\extra\httpd-vhosts.conf</strong>, and open it in notepad.</li>
<li>Find a line that says something like <strong>NameVirtualHost *:80</strong>. Remove the <strong>#</strong> sign that you see in front of it; this turns it from being a comment to code that is actually executed. (This was not in any instructions I could find)</li>
<li>
<p>Next, scroll to the bottom, and you can add multiple domains. Here is what mine looks like:</p>
<pre><code>&lt;VirtualHost *:80>
ServerAdmin webmaster@localhost.trevordavis.dev
DocumentRoot "C:/sites/trevordavis.dev/webpages"
ServerName localhost.trevordavis.dev
&lt;/VirtualHost>

&lt;VirtualHost *:80>
ServerAdmin webmaster@localhost.trevordavis.redesign
DocumentRoot "C:/sites/trevordavis.redesign/webpages"
ServerName localhost.trevordavis.redesign
&lt;/VirtualHost></code></pre>
</li>
<li>
<p>Finally, find this file: <strong>C:\WINDOWS\system32\drivers\etc\hosts</strong> and open it in notepad. You need to add an entry for each site you setup in the <strong>httpd-vhosts.conf</strong> file. My file looks like this:</p>
<pre><code>127.0.0.1 localhost
127.0.0.1 localhost.trevordavis.dev
127.0.0.1 localhost.trevordavis.redesign</code></pre>
</li>
</ol>
<h3 class="replaceHeadline">That&rsquo;s It</h3>
<p>Once you have done this you can browse to <strong>http://localhost.trevordavis.dev</strong> and <strong>http://localhost.trevordavis.redesign</strong> on your computer when you have your web server running. This means that you can view PHP files and execute SQL locally.</p>
<p>It&rsquo;s great.</p>
<p>Let me know if you have any questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/creating-multiple-sites-on-a-local-web-server/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Ajax Forms with jQuery</title>
		<link>http://trevordavis.net/blog/tutorial/ajax-forms-with-jquery/</link>
		<comments>http://trevordavis.net/blog/tutorial/ajax-forms-with-jquery/#comments</comments>
		<pubDate>Sat, 08 Sep 2007 05:13:07 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=30</guid>
		<description><![CDATA[There are so many different javascript frameworks out there, but I have recently started to use jQuery, and I love it. Not only is the library much smaller than others, but it is so simple to use. I wanted to show how easy it is to turn a regular form into a AJAX form.

Start with [...]]]></description>
			<content:encoded><![CDATA[<p>There are so many different javascript frameworks out there, but I have recently started to use <a href="http://jquery.com">jQuery</a>, and I love it. Not only is the library much smaller than others, but it is so simple to use. I wanted to show how easy it is to turn a regular form into a AJAX form.</p>
<p><span id="more-30"></span></p>
<h2 class="replaceHeadline">Start with a Regular Form</h2>
<p>First, I am going to build a <a href="http://trevordavis.net/play/jqueryAjaxForm/">regular form</a>. The form is just going to be a basic email form. You enter an email address to send to, an email address to send from, a subject, and a message. All fields are required. So the process of the form is:</p>
<ol>
<li>User fills out the form.</li>
<li>User submits the form to the server.</li>
<li>Server side script makes sure that there are no blank fields and that the email addresses are valid.</li>
<li>If there are errors, show the form again with the error messages.</li>
<li>If there are no errors, send the email.</li>
</ol>
<p>Ok, so this form is pretty simple, and doesn&rsquo;t take much time to submit since it&rsquo;s so short, but let&rsquo;s see how much better we can make it with a little jQuery.</p>
<h2 class="replaceHeadline">Add in JavaScript</h2>
<p>OK, so next, I am going to make an <a href="http://trevordavis.net/play/jqueryajaxform/ajaxed/">AJAX version, which is a duplicate of the first form</a>. The only other things I am going to include on the page are the jquery library (<a href="http://docs.jquery.com/Downloading_jQuery">which you can download here</a>) and my JavaScript to process this form.</p>
<h3 class="replaceHeadline">Firing My Script When the Document is Ready</h3>
<p>jQuery has a nice little function to have you script start when the document is ready:</p>
<pre><code>$(document).ready(function(){
	//Script goes here
});</code></pre>
<p>OK, easy enough. Now, let&rsquo;s make something happen when the button to submit the form is clicked. I was smart enough to add an id of <strong>submit</strong> to my button, so it makes it really easy to reference:</p>
<pre><code>$(document).ready(function(){
	$("#submit").click(function(){
		return false;
	});
});</code></pre>
<p>First things first, I&rsquo;m going to hide anything with the class of error if it&rsquo;s showing (which nothing will be unless the form is unsuccessfully submitted twice). I also create a variable that I am going to use later to see if the form has an error and a variable to store the email regular expression:</p>
<pre><code>$(document).ready(function(){
	$("#submit").click(function(){
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

		return false;
	});
});</code></pre>
<h3 class="replaceHeadline">Error Checking</h3>
<p>Now that we&rsquo;ve got the beginning of the script setup, we need to do the error checking. So first, let&rsquo;s check to make sure that the email to address is not empty or invalid:</p>
<pre><code>$(document).ready(function(){
	$("#submit").click(function(){
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

		var emailToVal = $("#emailTo").val();
		if(emailToVal == '') {
			$("#emailTo").after('&lt;span class="error">You forgot to enter the email address to send to&lt;/span>');
			hasError = true;
		} else if(!emailReg.test(emailToVal)) {
			$("#emailTo").after('&lt;span class="error">Enter a valid email address to send to.&lt;/span>');
			hasError = true;
		}

		return false;
	});
});</code></pre>
<p>Remember, the email address to send to input has an id of <strong>emailTo</strong>. What that code is saying is:</p>
<ul>
<li>Get the value of the email to address input.</li>
<li>If it is empty, add an error message after the input</li>
<li>If it has an invalid email address, add an error message after the input.</li>
</ul>
<p>Now, we just need to repeat the error checking for the other form fields:</p>
<pre><code>$(document).ready(function(){
	$("#submit").click(function(){
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

		var emailToVal = $("#emailTo").val();
		if(emailToVal == '') {
			$("#emailTo").after('&lt;span class="error">You forgot to enter the email address to send to.&lt;/span>');
			hasError = true;
		} else if(!emailReg.test(emailToVal)) {
			$("#emailTo").after('&lt;span class="error">Enter a valid email address to send to.&lt;/span>');
			hasError = true;
		}

		var emailFromVal = $("#emailFrom").val();
		if(emailFromVal == '') {
			$("#emailFrom").after('&lt;span class="error">You forgot to enter the email address to send from.&lt;/span>');
			hasError = true;
		} else if(!emailReg.test(emailFromVal)) {
			$("#emailFrom").after('&lt;span class="error">Enter a valid email address to send from.&lt;/span>');
			hasError = true;
		}

		var subjectVal = $("#subject").val();
		if(subjectVal == '') {
			$("#subject").after('&lt;span class="error">You forgot to enter the subject.&lt;/span>');
			hasError = true;
		}

		var messageVal = $("#message").val();
		if(messageVal == '') {
			$("#message").after('&lt;span class="error">You forgot to enter the message.&lt;/span>');
			hasError = true;
		}

		return false;
	});
});</code></pre>
<p>Ok, error checking is done. If there are no errors, we need to send the email via an AJAX request. I&rsquo;m not going to include the whole script here, just because it&rsquo;s getting long, but you can <a href="http://trevordavis.net/wp-content/uploads/2008/01/submitform.js">see the whole script</a>.</p>
<p>So, there are no errors. Let&rsquo;s remove the button from the form, and add in a loading graphic:</p>
<pre><code>if(hasError == false) {
	$(this).hide();
	$("#sendEmail li.buttons").append('&lt;img src="/images/template/loading.gif" alt="Loading" id="loading" />');
}</code></pre>
<h3 class="replaceHeadline">Submit the POST Request</h3>
<p>Ok, now let&rsquo;s send the values via an AJAX POST request to our send email script that just sends the email. Once the request is completed, let&rsquo;s hide the form and display a success message:</p>
<pre><code>$.post("/play/jqueryAjaxForm/sendEmail.php",
   { emailTo: emailToVal, emailFrom: emailFromVal, subject: subjectVal, message: messageVal },
   	function(data){
		$("#sendEmail").slideUp("normal", function() {

			$("#sendEmail").before('&lt;h1>Success&lt;/h1>&lt;p>Your email was sent.&lt;/p>');
		});
	}
);</code></pre>
<p>Pretty nice huh? So now, you have a perfectly accessible form. It works fine without JavaScript. But it works even better with JavaScript. I highly recommend checking out the <a href="http://docs.jquery.com/Main_Page">jQuery Documentation</a>. So go ahead, send yourself some emails to see for yourself.</p>
<h3 class="replaceHeadline">Update&hellip;</h3>
<p>I was asked in the comments if I could include the PHP script. So as requested, here are the files that are used:</p>
<ul>
<li><a href="http://trevordavis.net/wp-content/uploads/2008/01/index.phps">index.php</a></li>
<li><a href="http://trevordavis.net/wp-content/uploads/2008/01/verify.phps">verify.php</a></li>
<li><a href="http://trevordavis.net/wp-content/uploads/2008/01/sendemail.phps">sendEmail.php</a></li>
<li><a href="http://trevordavis.net/wp-content/uploads/2008/01/thanks.phps">thanks.php</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/ajax-forms-with-jquery/feed/</wfw:commentRss>
		<slash:comments>417</slash:comments>
		</item>
		<item>
		<title>Calculating Font Sizes</title>
		<link>http://trevordavis.net/blog/tutorial/calculating-font-sizes/</link>
		<comments>http://trevordavis.net/blog/tutorial/calculating-font-sizes/#comments</comments>
		<pubDate>Wed, 01 Aug 2007 03:05:02 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=27</guid>
		<description><![CDATA[There are a lot of articles out there about typography on the web. I wanted to explain my method of controlling font sizes and margins in CSS.
I love Dan Mall&#8217;s Soft Serve Technique, but then you have to make a special case for IE6. (Hopefully it won&#8217;t be too much longer that we have to [...]]]></description>
			<content:encoded><![CDATA[<p>There are a lot of articles out there about typography on the web. I wanted to explain my method of controlling font sizes and margins in CSS.</p>
<p>I love <a href="http://www.danielmall.com/archives/2007/04/20/soft_serve.php">Dan Mall&rsquo;s Soft Serve Technique</a>, but then you have to make a special case for IE6. (Hopefully it won&rsquo;t be too much longer that we have to worry about IE6).</p>
<p><span id="more-27"></span></p>
<h2 class="replaceHeadline">Getting a Usable Base Font Size</h2>
<p>Ok, so to start, I like setting the font size of the body to <em>62.5%</em>. I used to take Dan Cederholm&rsquo;s approach of setting the font size to <em>small</em>, but I finally realized that it did not give me a nice base font size to play with.</p>
<p>So by setting the font size of the body to <em>62.5%</em>, we get a base font size of 10px. This gives us a nice round number to work with. Thus, 1em now equals 10px. <span class="pullquote alt">10px is way too small to be the font size of the content though.</span> Thus, I just set the font size of the outter-most container to <em>1.2em</em>. Since we had a base size of 10px, our font size in the container becomes 12px.</p>
<h2 class="replaceHeadline">Heading Font Sizes</h2>
<p>The next thing I like to do is to set the font sizes of all of the headings, h1-h6. A good set of values for headings is:</p>
<ul>
<li>h1: 22px</li>
<li>h2: 20px</li>
<li>h3: 18px</li>
<li>h4: 16px</li>
<li>h5: 14px</li>
<li>h6: 12px</li>
</ul>
<p>Again, these are just values that I am suggesting, you could definitely choose whatever you want.</p>
<p>To get these font sizes, we just need to do some simple math.</p>
<h3 class="replaceHeadline">Example</h3>
<p>Let&rsquo;s use an h3 as an example. We take the size that we want the heading to be, 18px, and divide it by the container font size, 12px. So, 18/12 = 1.5. Then, we set the font size to either 1.5em or 150%. I personally like working with ems, although I used to prefer percentages.</p>
<p>So again, <span class="pullquote alt">font size we want to achieve / font size of the container</span>. Use this to compute the rest of your heading font sizes, and then you will have nice pixel values to work with.</p>
<h2 class="replaceHeadline">Attacking the Margins</h2>
<p>So obviously you want to avoid letting the browser control how your elements will be spaced, so let&rsquo;s work on setting the margins on these elements too.</p>
<h3 class="replaceHeadline">Remove the Default Margins</h3>
<p>The first thing I do in a stylesheet is zero out the margins and paddings:</p>
<pre><code>html, body, div, h1, h2, h3, h4, h5, h6, ul, ol, dl, li, dt, dd, p, blockquote, pre, form, th, td {
	margin: 0;
	padding: 0;
}</code></pre>
<p>Next, I set a bottom margin of 1em on p, ul, ol, dl, blockquote:</p>
<pre><code>p, ul, ol, dl, blockquote { margin-bottom: 1em; }</code></pre>
<p>Then, to get an equal amount of margin on the bottom of the headings, we just need to do more simple math. We can&rsquo;t just set the bottom margin to 1em because our font size on these elements are bigger than the rest of the content.</p>
<h4 class="replaceHeadline">Example</h4>
<p>So let&rsquo;s use the h3 as an example again. This time, we take the font size of the container, 12px, and diving it by the size of the heading, 18px. 12/18 = 0.667. So then, our h3 would look like this:</p>
<pre><code>h3 {
	font-size: 1.5em;
	margin-bottom: 0.667em;
}</code></pre>
<p>So again, <span class="pullquote alt">font size of the container / font size of the element</span>. If you do this for all elements, you will have an equal margin between all elements. I made a <a href="http://trevordavis.net/play/fontSize/">page showing elements with equal margins</a>.</p>
<p>I used to think this was best, but I have since realized that I like having the headings closer to the text that is following. So I divide the bottom margin on the headings by 4. Thus, we get a quarter of the margin above the heading, below it.</p>
<p>In my opinion, <a href="http://trevordavis.net/play/fontsize/example-2/">the example page with custom margins</a> looks much better.</p>
<p>Anyone else have other methods?</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/calculating-font-sizes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a Dynamic Google Sitemap</title>
		<link>http://trevordavis.net/blog/tutorial/creating-a-dynamic-google-sitemap/</link>
		<comments>http://trevordavis.net/blog/tutorial/creating-a-dynamic-google-sitemap/#comments</comments>
		<pubDate>Wed, 18 Jul 2007 02:13:16 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=26</guid>
		<description><![CDATA[My site has a Wordpress blog on it, but it does not power the whole site, just the blog. If my entire site were powered by Wordpress, then I could generate a sitemap for Google using Wordpress functions.
I did not want to have Wordpress control everything; I wanted to have more control. By doing some [...]]]></description>
			<content:encoded><![CDATA[<p>My site has a <a href="http://trevordavis.net/blog/news/switched-to-wordpress.php">Wordpress blog on it</a>, but it does not power the whole site, just the blog. If my entire site were powered by Wordpress, then I could generate a <a href="http://www.google.com/webmasters/sitemaps/">sitemap for Google</a> using Wordpress functions.</p>
<p>I did not want to have Wordpress control everything; I wanted to have more control. By doing some quick queries, you can generate a sitemap for Google that has all of your blog entries in it.</p>
<p><span id="more-26"></span></p>
<h2>Setting it Up</h2>
<p>First, you will need to send the correct headers, create the opening xml tag, and connect to your database.</p>
<pre><code>&lt;?php
header("Content-Type: text/xml;charset=iso-8859-1");
echo '&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
require_once('DB CONNECTION GOES HERE'); //This is where I would require my DB connection file</code></pre>
<p>If you are not sure how to connect to your database, you will need to contact your host to get that information, and then do a <a href="http://www.google.com/search?source=ig&amp;hl=en&amp;q=php+mysql+connection&amp;btnG=Google+Search">search for php MySQL connection</a>. If you can&rsquo;t figure it out still, <a href="/contact/">let me know, and I can help</a>.</p>
<h2>Get the Categories</h2>
<p>Next, we want to query the database to get the categories used in Wordpress:</p>
<pre><code>$query = "SELECT cat_ID, category_nicename
		FROM wp_categories
		ORDER BY category_nicename";
$result = @mysql_query($query);</code></pre>
<p>Then, we need to loop through the categories and display a url entry for each category:</p>
<pre><code>while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
	echo '&lt;url>
		&lt;loc>http://trevordavis.net/blog/' . $row['category_nicename'] . '/&lt;/loc>
		&lt;changefreq>weekly&lt;/changefreq>
	     &lt;/url>';</code></pre>
<h2>Get the Entries</h2>
<p>Next, we need to create a query to return all of the entries for each category:</p>
<pre><code>$artQuery = "SELECT p.post_name, DATE_FORMAT(p.post_date, '%Y-%m-%d') AS createdOn
		FROM wp_posts AS p, wp_categories AS cat, wp_post2cat AS pc
		WHERE p.ID = pc.post_id AND pc.category_id = " . $row['cat_ID'] . "
		GROUP BY p.ID
		ORDER BY p.ID DESC";
$artResult = @mysql_query($artQuery);</code></pre>
<p>Finally, we want to create a url entry for each blog entry:</p>
<pre><code>while($artRow = mysql_fetch_array($artResult, MYSQL_ASSOC)) {
	echo '&lt;url>
		&lt;loc>http://trevordavis.net/blog/' . $row['category_nicename'] . '/'. $artRow['post_name'] . '.php&lt;/loc>
		&lt;lastmod>'.$artRow['createdOn'].'&lt;/lastmod>
		&lt;changefreq>weekly&lt;/changefreq>
	     &lt;/url>';
}
</code></pre>
<p>To finish it off, we just close everything up:</p>
<pre><code>}
echo'&lt;/urlset>';?></code></pre>
<h3>The Whole Script</h3>
<p>Here is the finished script:</p>
<pre><code>&lt;?php
header("Content-Type: text/xml;charset=iso-8859-1");
echo '&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
require_once('DB CONNECTION GOES HERE'); //This is where I would require my DB connection file

$query = "SELECT cat_ID, category_nicename
		FROM wp_categories
		ORDER BY category_nicename";
$result = @mysql_query($query);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

	echo '&lt;url>
		&lt;loc>http://trevordavis.net/blog/' . $row['category_nicename'] . '/&lt;/loc>
		&lt;changefreq>weekly&lt;/changefreq>
	     &lt;/url>';

	$artQuery = "SELECT p.post_name, DATE_FORMAT(p.post_date, '%Y-%m-%d') AS createdOn
			FROM wp_posts AS p, wp_categories AS cat, wp_post2cat AS pc
			WHERE p.ID = pc.post_id AND pc.category_id = " . $row['cat_ID'] . "
			GROUP BY p.ID
			ORDER BY p.ID DESC";

	$artResult = @mysql_query($artQuery);

	while($artRow = mysql_fetch_array($artResult, MYSQL_ASSOC)) {

		echo '&lt;url>
			&lt;loc>http://trevordavis.net/blog/' . $row['category_nicename'] . '/'. $artRow['post_name'] . '.php&lt;/loc>
			&lt;lastmod>'.$artRow['createdOn'].'&lt;/lastmod>
			&lt;changefreq>weekly&lt;/changefreq>
		      &lt;/url>';
	}
}
echo'&lt;/urlset>';
?></code></pre>
<h3>Modifying the .htaccess file</h3>
<p>We also want to rewrite the url for this file so that it is available at <a href="http://trevordavis.net/sitemap.xml">http://trevordavis.net/sitemap.xml</a>. Open up your .htaccess file, or create one if you don&rsquo;t have one. Then add the following:</p>
<pre><code>RewriteEngine on
RewriteRule sitemap.xml googleSitemap.php</code></pre>
<p>Upload this file along with the googleSitemap.php script to your site root, and you are set. You can also add the rest of your site&rsquo;s file structure to the sitemap as well. You can see how I did this in <a href="http://trevordavis.net/sitemap.xml">my google sitemap</a>.</p>
<h3>Sitemaps Protocal</h3>
<p>You can <a href="http://sitemaps.org/protocol.php">read more about the sitemaps protocal</a> to see what other attributes you can apply to each url entry.</p>
<h3>By the Way&hellip;</h3>
<p>Let me know if you can think of any way to improve this.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/creating-a-dynamic-google-sitemap/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Centering Absolutely Positioned Items</title>
		<link>http://trevordavis.net/blog/tutorial/centering-absolutely-positioned-items/</link>
		<comments>http://trevordavis.net/blog/tutorial/centering-absolutely-positioned-items/#comments</comments>
		<pubDate>Sun, 08 Jul 2007 04:39:24 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=25</guid>
		<description><![CDATA[At work the other day, I was working on the homepage of a small save the date site. We had so many beautiful images to use, so our designer decided to limit the text that is on the homepage. So the container is absolutely positioned with a height of 100% in order to fill the [...]]]></description>
			<content:encoded><![CDATA[<p>At work the other day, I was working on the homepage of a small save the date site. We had so many beautiful images to use, so our designer decided to limit the text that is on the homepage. So the container is absolutely positioned with a height of 100% in order to fill the viewport.</p>
<p>The client wrote back right before we were ready to launch and said that they noticed a large white margin on the right hand side. We had to explain to them that since the design was left aligned and the picture can&rsquo;t go on forever, there has to be an end to the design. We decided to center the design in order to make it look better.</p>
<p>So I went in and added <code>margin: 0 auto</code> like I normally would to center anything, but then I realized since it is absolutely positioned, it would&rsquo;t work like that.</p>
<p><span id="more-25"></span></p>
<h2>How to Center the Absolute Positioned Item</h2>
<p>After doing some thinking, I thought about positioning the item from the left edge a certain percent. So I thought if I moved it over 50% and then shifted it back to the right, then it should work.</p>
<h3>Example</h3>
<p>Here is the CSS that I started with:</p>
<pre><code>div#centered {
	height: 300px;
	left: 50%;
	position: absolute;
	top: 20px;
	width: 500px;
}</code></pre>
<p>Ok, so now we&rsquo;ve got it shifted over 50% from the left hand side, and in order to get it back to the center, you need to take half of the width of the item, in this case <strong>250px</strong>.</p>
<p>So if we set a negative left margin of <strong>-250px</strong>, we end up with the following CSS:</p>
<pre><code>div#centered {
	height: 300px;
	left: 50%;
	margin-left: -250px;
	position: absolute;
	top: 20px;
	width: 500px;
}</code></pre>
<p>You can see that <a href="http://trevordavis.net/play/absolutePositionCenter/">the absolutely positioned item is now centered</a>.</p>
<h2>In Case You Didn&rsquo;t Notice&hellip;</h2>
<p>I alphabetize my CSS properties. It makes everything so much easier to maintain. Once you actually start to think about it, it pretty much comes naturally too. Give it a shot.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/centering-absolutely-positioned-items/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic Bread Crumbs</title>
		<link>http://trevordavis.net/blog/tutorial/dynamic-bread-crumbs/</link>
		<comments>http://trevordavis.net/blog/tutorial/dynamic-bread-crumbs/#comments</comments>
		<pubDate>Sun, 24 Jun 2007 04:28:12 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=23</guid>
		<description><![CDATA[For a redesign project at work, the new design called for bread crumbs. In my opinion, bread crumbs are a great thing to add to a site, and others agree. I didn&#8217;t want to have to specify anything on each page for the bread crumbs to work, so I wanted to do it all dynamically.
For [...]]]></description>
			<content:encoded><![CDATA[<p>For a redesign project at work, the new design called for bread crumbs. In my opinion, bread crumbs are a great thing to add to a site, and <a href="http://www.useit.com/alertbox/breadcrumbs.html">others agree</a>. I didn&rsquo;t want to have to specify anything on each page for the bread crumbs to work, so I wanted to do it all dynamically.</p>
<p>For the project at work, I did it in ColdFusion; but on my own, I did it in PHP. I figured the way that I would have to do it would be to parse the URL to see which folders I was in.</p>
<p><span id="more-23"></span></p>
<h2 class="replaceHeadline">The Code</h2>
<p>File: breadcrumbs.php</p>
<pre><code>&lt;?php require('buildbreadcrumbs.php'); ?>

&lt;ol id="breadCrumbs">
	&lt;li class="first">&lt;a href="/">Home&lt;/a>&lt;/li>
&lt;?php
	$breadCrumbs = $_SERVER['REQUEST_URI'];
	if($breadCrumbs != '') {
		$crumbUrl = '/';
		$toks = split('/', $breadCrumbs);
		for($i = 1; $i < count($toks) - 1; $i++) {
			$crumbUrl .= $toks[$i] . '/';
			if($breadCrumbMapping[$toks[$i]] != NULL) {
				echo '&lt;li>&lt;a href="'.$crumbUrl.'">'.$breadCrumbMapping[$toks[$i]].'&lt;/a>&lt;/li>';
			} else {
				echo '&lt;li>&lt;a href="'.$crumbUrl.'">'.$toks[$i].'&lt;/a>&lt;/li>';
			}
		}
		echo '&lt;li class="last">'.$pageTitle.'&lt;/li>';
	}
?>
&lt;/ol></code></pre>
<h3 class="replaceHeadline">The Explanation</h3>
<p>The first thing that I do, is include the file buildbreadcrumbs.php (I&rsquo;ll get to that later). Then the idea is that we will determine what folders we are in, based on the URL. We split the URL based on the slashes and step through them to make links.</p>
<p>Now, back to the File: buildbreadcrumbs.php</p>
<pre><code>&lt;?php
$breadCrumbMapping = Array();

/*Folders to be mapped*/
$breadCrumbMapping['f1'] = "Folder 1";
$breadCrumbMapping['f2'] = "Folder 2";
$breadCrumbMapping['f3'] = "Folder 3";
?></code></pre>
<p>This file is building as associative array to display different text than the folder name. There are some situations where the folders are not too pretty, so basically you just add the folder name (f1, f2, f3) to the associative array and assign it a &ldquo;pretty&rdquo; name (Folder 1, Folder 2, Folder 3). If you don&rsquo;t assign a pretty name to a folder, it will just display the folder name instead.</p>
<p>I made <a href="http://trevordavis.net/play/breadCrumbs/f1/f2/f3/">an example page</a> to see the bread crumbs in action.</p>
<p>You can download the scripts here:</p>
<ul>
<li><a href="http://trevordavis.net/wp-content/uploads/2008/01/breadcrumbs.phps">breadcrumbs.php</a></li>
<li><a href="http://trevordavis.net/wp-content/uploads/2008/01/buildbreadcrumbs.phps">buildbreadcrumbs.php</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/dynamic-bread-crumbs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Dean Edwards&#8217; IE7 Script</title>
		<link>http://trevordavis.net/blog/tutorial/using-dean-edwards-ie7-script/</link>
		<comments>http://trevordavis.net/blog/tutorial/using-dean-edwards-ie7-script/#comments</comments>
		<pubDate>Tue, 08 May 2007 02:56:04 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=17</guid>
		<description><![CDATA[Update
Dean Edwards has updated his scripts. I have written a new entry describing the updated IE7 scripts.

At An Event Apart Boston, Eric Meyer discussed how IE7 is quickly being adopted. Since this is the case, we can treat IE6 as more of a secondary browser now.
We should all start to use the Dean Edwards IE7 [...]]]></description>
			<content:encoded><![CDATA[<div class="update">
<h2 class="replaceHeadline">Update</h2>
<p>Dean Edwards has updated his scripts. I have written a <a href="http://trevordavis.net/blog/tutorial/updated-dean-edwards-ie7-scripts/">new entry describing the updated IE7 scripts</a>.</p>
</div>
<p>At An Event Apart Boston, <a href="http://meyerweb.com">Eric Meyer</a> discussed how IE7 is quickly being adopted. Since this is the case, we can treat IE6 as more of a secondary browser now.</p>
<p>We should all start to use the <a href="http://dean.edwards.name/ie7/">Dean Edwards IE7 script</a> to bring IE6 up to par with standards compliant browsers.</p>
<p><span id="more-17"></span></p>
<p>The history behind the Dean Edwards script is that he wrote it when Microsoft had said that they were not going to produce any more versions of Internet Explorer. He wanted to provide a JavaScript solution to add more compliance to the browser.</p>
<h2 class="replaceHeadline">Using the Script</h2>
<p>First, <a href="http://dean.edwards.name/download/">download the Dean Edwards script</a>. Next, extract the files to the root of your webserver in a folder called <strong>ie7</strong>. It needs to be in this folder, because some of the scripts have a dependency on the folder.</p>
<p>Finally, just include the script in the head of your document using conditional comments:</p>
<pre><code>&lt;!--[if lt IE 7]>
&lt;script src="/ie7/ie7-standard-p.js" type="text/javascript">&lt;/script>
&lt;![endif]--></code></pre>
<p>On <a href="http://dean.edwards.name/IE7/usage/configure.html">the configuration page</a>, Dean shows you which scripts do what. By including the <code>ie7-standard-p.js</code>, you get the support of the following scripts:</p>
<ul>
<li>ie7-core.js</li>
<li>ie7-html4.js</li>
<li>ie7-layout.js</li>
<li>ie7-css2-selectors.js</li>
<li>ie7-graphics.js</li>
<li>ie7-fixed.js</li>
</ul>
<p>The only other script that I have included as well is the <code>ie7-css3-selectors.js</code> to include support for CSS3 selectors. Think of all those wonderful <a href="http://trevordavis.net/blog/tutorial/css-attribute-selectors-explained.php">attribute selectors</a> you can start to use in your project. It makes me all warm and tingly inside to think about where CSS can go when the browsers are up to the task.</p>
<h3 class="replaceHeadline">Enjoy!</h3>
<p>This really should be one of the first steps you take in a project. By doing this simple task, you will save yourself from a lot of IE6 headaches.</p>
<p>Sure, this only works for IE6 users who have JavaScript enabled. But honestly, is there anyone who is using IE6 who actually turns off JavaScript? If they do turn off JavaScript, it may just break some presentation layer things, but the site should still be perfectly usable.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/using-dean-edwards-ie7-script/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Improved Navigation Image Replacement</title>
		<link>http://trevordavis.net/blog/tutorial/improved-navigation-image-replacement/</link>
		<comments>http://trevordavis.net/blog/tutorial/improved-navigation-image-replacement/#comments</comments>
		<pubDate>Sat, 28 Apr 2007 03:32:42 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=15</guid>
		<description><![CDATA[So my co-worker at work today was slicing a design, and the designer said that the navigation had to be images. Being the good little accessibility people that we were, we were trying to figure out a way to use images, but have text also show up when images are disabled.
So my co-worker went with [...]]]></description>
			<content:encoded><![CDATA[<p>So my co-worker at work today was slicing a design, and the designer said that the navigation had to be images. Being the good little accessibility people that we were, we were trying to figure out a way to use images, but have text also show up when images are disabled.</p>
<p>So my co-worker went with the quick fix (for now), a JavaScript onmouseover solution, and I told him that it was lame. I told him there had to be a way to use CSS to do it. I didn&#8217;t have time to do it at work, so I played with it, and I have found a solution.</p>
<p><span id="more-15"></span></p>
<h2 class="replaceHeadline">The Markup</h2>
<p>Ok, so everyone knows to mark-up navigation in an unordered list:</p>
<pre><code>&lt;ul id="nav">
	&lt;li>&lt;a href="#">Text to Cover Here&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Text to Cover Here&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Text to Cover Here&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Text to Cover Here&lt;/a>&lt;/li>
&lt;/ul></code></pre>
<p>Now, instead of placing an image in the anchor tag and then using JavaScript to change the hover state, I thought, why not just add an extra <code>span</code> at the end of the anchor tag. I chose the end, but it also works with it at the beginning. I think it makes more sense to have it at the end though, so that the text within the anchor tag is read first by screen readers and bots. So this is what our markup looks like now:</p>
<pre><code>&lt;ul id="nav">
	&lt;li>&lt;a href="#">Text to Cover Here&lt;span>&lt;/span>&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Text to Cover Here&lt;span>&lt;/span>&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Text to Cover Here&lt;span>&lt;/span>&lt;/a>&lt;/li>
	&lt;li>&lt;a href="#">Text to Cover Here&lt;span>&lt;/span>&lt;/a>&lt;/li>
&lt;/ul></code></pre>
<h2 class="replaceHeadline">Let&rsquo;s Style It</h2>
<p>So I started off with just some normal styles that you would apply to a navigation: zeroing out margins and paddings, floating it, removing the list-styling, and giving it a width.</p>
<p>Next, I floated the list items so that they would be in a line horizontally. This is where it finally gets interesting, I promise. I styled the anchor tag like so:</p>
<pre><code>ul#nav li a {
	background: #FFFF99;
	display: block;
	height: 30px;
	padding: 0 5px;
	width: 115px;
}</code></pre>
<p>Since this is just an example, I put a random background color on (to make sure it didn&rsquo;t show through in the final example), and I gave them all the same width. Not a likely situation, but I didn&rsquo;t feel like giving each list item an id. That should be self explanatory enough.</p>
<p>Now, when I think back to the talk that <a href="http://meyerweb.com">Eric Meyer</a> at <a href="http://aneventapart.com/events/boston07/">An Event Apart Boston</a>, he kept stressing that to a browser, an element is just an element, and you can do anything to it. So, my plan was to just set the anchor tag to be relatively positioned so that it would contain the <code>span</code>.</p>
<p>The next step is to add the background image to the <code>span</code>. Now one thing that needs to be realized is that you cannot use a transparent image. But I don&rsquo;t think that really causes much of a problem in most cases.</p>
<pre><code>ul#nav li a span {
	background: url(/wp-content/uploads/2008/01/nav.gif) no-repeat 0 -30px;
	cursor: pointer;
	display: block;
	height: 30px;
	left: 0;
	position: absolute;
	top: 0;
	width: 125px;
}</code></pre>
<p>The only things to note from that is that I combined the normal and hover states into one awesome image (I wasn&rsquo;t worried about how pretty it looked). I also had to add the cursor property for our best friend, IE6.</p>
<p>Ok, cool. We are on our way. Now we just need to shift the background image on the hover state:</p>
<pre><code>ul#nav li a:hover span { background: url(/wp-content/uploads/2008/01/nav.gif) no-repeat 0 0; }</code></pre>
<p><strong>Voil&agrave;!</strong> It works like a charm. <a href="http://trevordavis.net/play/imagereplacement/">Check out the example</a>.</p>
<h3 class="replaceHeadline">But&hellip;</h3>
<p>Did you check it in IE6? When I checked it in Firefox and IE7, everything worked beautifully. You can turn off the images and you get the text underneath.</p>
<p>When you do check it in IE6, you will notice that the hover states stay on. It&rsquo;s very odd.</p>
<p>After a lot of tinkering, I finally found something that worked. If you add the following to the anchor when it is in its hovered state, it for some reason fixes it:</p>
<pre><code>ul#nav li a:hover { background: 0 0; }</code></pre>
<p>I have no explanation, but it does not seem to have any adverse affects on other browsers.</p>
<h3 class="replaceHeadline">Let&rsquo;s Bulletproof It</h3>
<p>We can add a simple property to the anchor tag so that when someone resizes their text, it does not poke out from under the image:</p>
<pre><code>ul#nav li a {
	background: #FFFF99;
	display: block;
	height: 30px;
	overflow: hidden; /*Added for bulletproofing*/
	padding: 0 5px;
	position: relative;
	width: 115px;
}</code></pre>
<p><a href="http://trevordavis.net/play/imagereplacement/final/">Check out the final example.</a></p>
<h3 class="replaceHeadline">More Bulletproofing</h3>
<p>If you wanted the text to resize gracefully when images are disabled, I suppose you could set your height in ems. Then you would just need to build some extra blank space into your image, so that it would work when images are enabled.</p>
<p>So hopefully that helps out my co-worker. I think it potentially solves a pretty big problem with CSS image navigation with images disabled.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/improved-navigation-image-replacement/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Improved JavaScript Striping</title>
		<link>http://trevordavis.net/blog/tutorial/improved-javascript-striping/</link>
		<comments>http://trevordavis.net/blog/tutorial/improved-javascript-striping/#comments</comments>
		<pubDate>Wed, 25 Apr 2007 02:14:02 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=14</guid>
		<description><![CDATA[I am sure everyone has seen the JavaScript Splintered Striper, which was shown during the 2005 24 Ways to Impress Your Friends, or at least some variation of it. A quick Google for javascript striper came up with a ton of results.
Well, I ran into a little problem with the splintered striper, and I have [...]]]></description>
			<content:encoded><![CDATA[<p>I am sure everyone has seen the <a href="http://24ways.org/2005/splintered-striper">JavaScript Splintered Striper</a>, which was shown during the 2005 <a href="http://24ways.org">24 Ways to Impress Your Friends</a>, or at least some variation of it. A <a href="http://www.google.com/search?source=ig&amp;hl=en&amp;q=javascript+%2B+striper&amp;btnG=Google+Search">quick Google for javascript striper</a> came up with a ton of results.</p>
<p>Well, I ran into a little problem with the splintered striper, and I have a solution to the problem.</p>
<p><span id="more-14"></span></p>
<p>The problem occurred if you had multiple class names on the element you are trying to stripe. That may not make much sense, so I guess an example will suffice.</p>
<h2>Striping Example with Problem</h2>
<p>Say we start with the following markup:</p>
<pre><code>&lt;ul class="stripe something">
	&lt;li>This is an odd row.&lt;/li>
	&lt;li>This is an even row.&lt;/li>
	&lt;li>This is an odd row.&lt;/li>
	&lt;li>This is an even row.&lt;/li>
	&lt;li>This is an odd row.&lt;/li>
	&lt;li>This is an even row.&lt;/li>
&lt;/ul></code></pre>
<p>We are going to pretend that the class name <code>something</code> actually does something useful. Then using a JavaScript <a href="http://simonwillison.net/2004/May/26/addLoadEvent/">addLoadEvent function</a>, we will add the striping event to run on page load:</p>
<pre><code>addLoadEvent(function() {
  striper('ul','stripe','li','odd,even');
});</code></pre>
<p>Essentially, we have told the striper function to stripe all list elements (<code>li</code>s) that are descendants of unordered lists (<code>ul</code>s) with the class name of stripe. Then we want to apply the classes odd and even to the alternating list items.</p>
<p>Here is where the problem lies. Since there are two classes on the unordered list, the striper function does not recognize that it has a class name of stripe. Here is the problem in the code:</p>
<pre><code>if ((parentElementClass == null)||(currentParent.className == parentElementClass)) {</code></pre>
<p>Since we are just seeing if the class name of the current element is equal to the class name of stripe, this is not true.</p>
<p>I have created a <a href="http://trevordavis.net/play/striper/indexBad.html">simple demo page</a> with an unordered list, table, and paragraphs that are supposed to be striped.</p>
<h2>Fixing the Striper</h2>
<p>Really all you have to do to the JavaScript is to remove the line from above and replace with the lines below:</p>
<pre><code>var pattern = new RegExp("(^| )" + parentElementClass + "( |$)");
if ((parentElementClass == null)||(currentParent.className.match(pattern))) {</code></pre>
<p>That takes the class name and splits is with a regular expression. So now you could have fifty class names on the element, and it will still work</p>
<p>Here is a <a href="http://trevordavis.net/play/striper/">little demo of the improved splintered striper</a>.</p>
<p>I&rsquo;m sure there is another way to do that easier, so feel free to let me know if there is.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/improved-javascript-striping/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSS Attribute Selectors Explained</title>
		<link>http://trevordavis.net/blog/tutorial/css-attribute-selectors-explained/</link>
		<comments>http://trevordavis.net/blog/tutorial/css-attribute-selectors-explained/#comments</comments>
		<pubDate>Sun, 15 Apr 2007 02:08:05 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=12</guid>
		<description><![CDATA[So, I had played around with CSS attribute selectors a little bit before I went to An Event Apart Boston, but I have a much better grasp of them now. I gave a brief overview in my An Event Apart Boston Summary.
Currently, you really have to do some digging to figure out exactly how to [...]]]></description>
			<content:encoded><![CDATA[<p>So, I had played around with CSS attribute selectors a little bit before I went to <a href="http://aneventapart.com/events/boston07/">An Event Apart Boston</a>, but I have a much better grasp of them now. I gave a brief overview in my <a href="http://trevordavis.net/blog/web/an-event-apart-boston-summary.php">An Event Apart Boston Summary</a>.</p>
<p>Currently, you really have to do some digging to figure out exactly how to use them, but I hope this article explains them all better.</p>
<p><span id="more-12"></span></p>
<h2 class="replaceHeadline">General Information</h2>
<p>Basically, attribute selectors allow you to target elements based on their attributes (i.e. alt, href, title, etc.). In the table below, you can see all the different options for attribute selectors.</p>
<dl>
<dt>[attr]</dt>
<dd>Whenever the attribute is set. Ex: input[type]</dd>
<dt>[attr="val"]</dt>
<dd>Whenever the attribute equals the specific value. Ex: input[type="radio"]</dd>
<dt>[attr~="val"]</dt>
<dd>Whenever the attribute equals one of the space separated list of values. Ex: input[type~="radio checkbox"]</dd>
<dt>[attr|="val"]</dt>
<dd>Whenever the attribute equals a hyphen-separated list of words, beginning with the value. (This one is supposed to be unreliable, and I am a little confused by the specifications, so I am not really sure of how to explain an example.)</dd>
<dt>[attr*="val"]</dt>
<dd>Whenever the attribute contains the value. Ex: a[href*=".com"]</dd>
<dt>[attr^="val"]</dt>
<dd>Whenever the attribute starts with the value. Ex: a[href^="http"]</dd>
<dt>[attr$="val"]</dt>
<dd>Whenever the attribute ends with the value. Ex: a[href$=".pdf"]</dd>
</dl>
<p>Ok, so hopefully the general information makes them a little clearer, and I hope the following examples make them very easy to use.</p>
<h2 class="replaceHeadline">Examples</h2>
<p>Below, I will give an example of each attribute selector and how it can be used.</p>
<h3 class="replaceHeadline">[attr]</h3>
<p>Ok, so say maybe you want to style anchors that have the href attribute set to something. This may help differentiate JavaScript anchors.</p>
<p>The CSS you want to add is like so:</p>
<pre><code>a { text-decoration: underline; }

a[href] {
	border-bottom: 1px dotted #999;
	text-decoration: none;
}
</code></pre>
<p>That will remove the underline, and add a grey bottom border to anything that has the href attribute set.</p>
<h3 class="replaceHeadline">[attr="val"]</h3>
<p>Ok, so maybe you have added a green border to all input elements, but then you don&rsquo;t want them on radio buttons. So you add the following CSS:</p>
<pre><code>input { border: 1px solid green; }

input[type="radio"] { border: none; }
</code></pre>
<p>That will add a green border to all input elements except for radio buttons.</p>
<h3 class="replaceHeadline">[attr~="val"]</h3>
<p>Use the same example that you want to add a green border to all input elements except for radio buttons, checkboxes, and submit buttons. The CSS you need is:</p>
<pre><code>input { border: 1px solid green; }

input[type~="radio checkbox submit"] { border: none; }
</code></pre>
<p>So you get a green border on all input elements except radio buttons, checkboxes, and submit buttons.</p>
<h3 class="replaceHeadline">[attr*="val"]</h3>
<p>Ok, so maybe you want to add a <a href="http://google.com">Google</a> favicon to every link to Google. Add the following (pretending you have a Google favicon):</p>
<pre><code>a[href*="google"] {
	background: url(/images/googleIcon.gif) no-repeat 100% 50%;
	padding-right: 25px;
}
</code></pre>
<p>So now any link to Google, http://google.com/analytics, http://google.com/sitemaps, etc. will have the Google favicon.</p>
<h3 class="replaceHeadline">[attr^="val"]</h3>
<p>Let&rsquo;s add an external link to all links that start with http</p>
<pre><code>a[href^="http"] {
	background: url(/images/external.gif) no-repeat 100% 50%;
	padding-right: 25px;
}
</code></pre>
<p>Now every link that starts with http will have an external link icon.</p>
<h3 class="replaceHeadline">[attr$="val"]</h3>
<p>Ok, now we should display an icon for any file types that we are linking to: pdf, doc, xls.</p>
<pre><code>a[href$=".pdf"], a[href$=".doc"], a[href$=".xls"] {
	background-position: 100% 50%;
	background-repeat: no-repeat;
	padding-right: 19px;
}

a[href$=".pdf"] { background-image: url(/images/pdf.gif); }
a[href$=".doc"] { background-image: url(/images/doc.gif); }
a[href$=".xls"] { background-image: url(/images/xls.gif); }
</code></pre>
<p>This is one of the coolest things for me. No more adding extraneous markup in order to add an icon that shows the file type when linking to a file.</p>
<h3 class="replaceHeadline">That&rsquo;s it!</h3>
<p>I must say, that this works in all browsers, except IE 6 of course. But if you use the <a href="http://dean.edwards.name/ie7/">Dean Edwards IE7 Script</a> and include the CSS 3 selectors, it will work. I will eventually give a rundown of how to use that script, because I find the documentation a little hard to read. So I hope everyone enjoys attribute selectors as much as I do.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/css-attribute-selectors-explained/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>CSS Forms</title>
		<link>http://trevordavis.net/blog/tutorial/css-forms/</link>
		<comments>http://trevordavis.net/blog/tutorial/css-forms/#comments</comments>
		<pubDate>Fri, 26 Jan 2007 04:40:41 +0000</pubDate>
		<dc:creator>Trevor</dc:creator>
				<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://trevordavis.net/?p=4</guid>
		<description><![CDATA[Everyone hates forms.
They are hard to style so that they work with your site design. They are hard to make them accessible. Yeah, yeah we have heard it all. But in reality, they are not that hard to do.
Since every other web developer/designer has their own method, I thought I would share my two cents.

When [...]]]></description>
			<content:encoded><![CDATA[<p>Everyone hates forms.</p>
<p>They are hard to style so that they work with your site design. They are hard to make them accessible. Yeah, yeah we have heard it all. But in reality, they are not that hard to do.</p>
<p>Since every other web developer/designer has their own method, I thought I would share my two cents.</p>
<p><span id="more-4"></span></p>
<p>When thinking through all of the HTML elements to find something that makes sense for forms, there are many options.</p>
<ul>
<li>Unordered List</li>
<li>Ordered List</li>
<li>DIVs</li>
<li>Paragraphs</li>
<li>Tables (Yes some people still use tables for forms)</li>
</ul>
<p>There are probably others. But I like to use a more uncommon element: a Definition List. It is perfect for the job. You have got the definition term, which is essentially like the label. Then you have got the definition description, which is basically the actual form element.</p>
<p>Let&#8217;s start with some un-styled markup:</p>
<pre><code>
&lt;form action="#" method="post" name="sendToFriendForm" id="sendToFriendForm">
	&lt;dl class="forms">
		&lt;dt>&lt;label for="name">Your Name:&lt;/label>&lt;/dt>
		&lt;dd>&lt;input name="name" id="name" type="text" />&lt;/dd>

		&lt;dt>&lt;label for="senderEmail">Your Email Address: &lt;span class="required">*&lt;/span>&lt;/label>&lt;/dt>
		&lt;dd>&lt;input name="senderEmail" id="senderEmail" type="text" />&lt;/dd>

		&lt;dt>&lt;label for="recipientEmail">Friend's Email Address: &lt;span class="required">*&lt;/span>&lt;/label>&lt;/dt>
		&lt;dd>&lt;input name="recipientEmail" id="recipientEmail" type="text" />&lt;/dd>
		&lt;dd class="help">Use commas to separate multiple email addresses.&lt;/dd>

		&lt;dt>&lt;label for="sex">Sex&lt;/label>&lt;/dt>
		&lt;dd class="radio">&lt;input name="sex" id="male" type="radio" /> &lt;label for="male">Male&lt;/label> &lt;input name="sex" id="female" type="radio" /> &lt;label for="female">Female&lt;/label>&lt;/dd>
		&lt;dt>&lt;label for="message">Message:&lt;/label>&lt;/dt>
		&lt;dd>&lt;textarea name="message" id="message">&lt;/textarea>&lt;/dd>
	&lt;/dl>
	&lt;button type="submit">Submit &raquo;&lt;/button>
&lt;/form>
</code></pre>
<p>I have created the page so you can see <a href="http://trevordavis.net/play/cssForms/">the output</a>. Even un-styled, this form doesn&#8217;t even look bad. But lets add some style:</p>
<pre><code>
	form {
		margin: 0;
		padding: 0;
	}

	dl.forms {
		float: left;
		width: 100%;
	}

	dl.forms dt {
		margin: 0;
		padding: 10px 0 0 0;
		clear: left;
		float: left;
		width: 175px;
	}

	dl.forms label { font-weight: bold; }

	dl.forms dd {
		margin: 0;
		padding: 10px 0 0 0;
	}

	dl.forms dd.help {
		clear: left;
		padding-top: 2px;
		font-size: 90%;
		color: #999;
	}

	dl.forms input, dl.forms textarea { width: 300px; }

	dl.forms dd.radio input { width: auto; }

	dl.forms textarea { height: 150px; }

	.required {
		color: #FF0000;
		font-weight: bold;
	}
</code></pre>
<p>I don&#8217;t think I need to go step by step through that because it is pretty simple styling. I have <a href="http://trevordavis.net/play/cssforms/final/">created the styled page</a> for you to see.</p>
<p>I personally like forms that have the label and the input element on the same line, but that&#8217;s just me. It is pretty flexible, try resizing the font two times. Still very readable. You could easily do the widths in ems or percentages; I just chose to use pixels since I don&#8217;t have any parent element containing it.</p>
<p>Should be pretty good in all browsers, especially since we didn&#8217;t do any crazy CSS. I know it looks good in FF, IE6 and IE7. I believe it works fine in Safari and Opera.</p>
<p>Obviously this isn&#8217;t the be all and end all to styling forms with CSS. But it is something to start with. So, go out and make it better. But be sure to share what you have created.</p>
]]></content:encoded>
			<wfw:commentRss>http://trevordavis.net/blog/tutorial/css-forms/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
