Wednesday, March 28, 2012

Progressive And Responsive Navigation



Progressive And Responsive Navigation



Developing for the Web can be a difficult yet rewarding job. Given the number of browsers across the number of platforms, it can sometimes be a bit overwhelming. But if we start coding with a little forethought and apply the principles of progressive enhancement from the beginning and apply some responsive practices at the end, we can easily accommodate for less-capable browsers and reward those with modern browsers in both desktop and mobile environments.
screenshot

A Common Structure

Below is the HTML structure of a navigation menu created by WordPress. This unordered list is pretty common for content management systems and hand-coded websites alike. This will be the basis for our work.
Please note: Any ellipses (…) in the snippets below stand in for code that we have already covered. We have used them to shorten the code and highlight the parts that are relevant to that section.
<nav class="main-navigation">
<ul>
<li><a href="#home">Home</a></li>
<li>
<a href="#about">About Us</a>
<ul class="children">
<li><a href="#leadership">Leadership</a></li>
<li><a href="#involvement">Involvement</a></li>
<li><a href="#vision">Our Vision</a></li>
</ul>
</li>
<li><a href="#clients">Our Clients</a></li>
<li>
<a href="#support">Support</a>
<ul class="children">
<li><a href="#blog">Blog</a></li>
<li><a href="#downloads">Downloads</a></li>
<li><a href="#faq">FAQ</a></li>
</ul>
</li>
<li><a href="#contact">Contact Us</a></li>
</ul>
</nav>
Unstyled Navigation

Our navigation, unstyled.

Our Tools

  • CSS Reset
  • HTML5 elements
  • LESS CSS
  • jQuery

CSS Reset

Resetting our CSS styles is where we’ll start. Browsers have different default styles for the elements we’ll be using, so understanding this and getting all of the elements to look the same is important. In this example, since we’re using an unordered list, there will be default left padding, top and bottom margins, and a list-style. You can either deal with these individually or, if you’re project will include more than just this navigation, use a reset to clear all of the styles and start fresh. I prefer Eric Meyer’s Reset CSS, but there are a few others to choose from, listed below. Whichever you choose, make sure it accounts for the new HTML5 elements.

HTML5 and CSS3 Elements

We’ll be wrapping the menu in HTML5’s nav element, which is one HTML5 feature that we should be using right now. If you need more good reasons to use HTML5 in your daily work, such as accessibility, then read “Top 10 Reasons to Use HTML5 Right Now” over at Codrops.
CSS3 will give our menu the progressive feel we’re looking for. We can use nifty effects such as linear gradients, text and box shadows and rounded corners, while providing a reasonable appearance for browsers that are dragging their feet. You could also consider using something like CSS3 Pie in the process. This will give those lagging browsers most of the functionality they lack to display your CSS3 properties.

LESS CSS

To make our CSS more efficient, we’ll use LESS along with a class file to ease the difficulty of dealing with all of those browser prefixes. Other options, such as Sass and Compass, do effectively the same thing and might better fit your particular development environment. If you’re interested in learning more about LESS and how it compares to Sass, check out another article of mine, “An Introduction to LESS, and Comparison to Sass.”

jQuery

To make our navigation a little friendlier in small browsers, such as those on mobile devices, we’ll use JavaScript. Essentially, we will gather all of the elements in our navigation and reorganize them into a select form element. Then, when the user selects an option from the list, they will navigate to that page. Interaction with a select element is one of the easiest and best ways to handle navigation in a small window. The practice is pretty common as well, so the learning curve for users will be gentler.

Getting Started

After applying a reset, we get something like the following. You can see that the margins, padding and list styles have been cleared.
Reset navigation

Reset navigation

Child-Level Menus

For now, the child-level menus will only get in the way. The best thing to do is remove them from the equation and add them back in when it’s time to style them. To achieve this, we will apply position: relative to all of the list elements, and move the children off screen until they are needed.
.main-navigation {
li {
position: relative;
}
.children {
left: -999em;
position: absolute;
}
}
Applying left: -999em; position: absolute; will move the children to the left of the screen by a significant margin. This method is preferable to just using display: none because it is more accessible to screen readers.
Unstyled without children

Unstyled without children

Common Navigation Styles

Every navigation menu will probably have links in it. But these links are not like the links we see in the main body of the page, which are blue, underlined and distinguishable from the surrounding text. Rather, links in the navigation will stand alone, and their function will be obvious. That being said, the links in a nav element will probably have a few features of their own that distinguish them from typical anchor tags.
nav {
a {
color: inherit;
display: block;
text-decoration: none;
}
}
Thus, a link will inherit the color of the text assigned to the parent element, in this case nav. It will be set to display as a block-level element, because we want the clickable area to be large and we do not want underlining (because that would just look funny).
Navigation with more functional links

Navigation with more functional links
Please note: color: inherit is not supported in IE 6 or 7. If you need to support those browsers, then you will need to explicitly set the color that you want.

Lining Up

Getting the menu in line calls for the use of floats. Initially, we’ll float all of the elements in the nav element to the left. Later, we’ll undo this property for the child-level menus, along with a lot of the other styles that we’ll set along the way.
.main-navigation {
ul, li, a {
float: left;
}
…
}
Inline navigation

Inline navigation
Because every element in the nav element is now floated, the element itself will collapse as though it were empty. There are a few ways to deal with this. One is to also float the nav element itself, which will expand it to wrap around its contents. If need be, you can set it to width: 100% to fill any remaining space to the right. Or you could use Nicolas Gallagher’s “micro” clearfix solution, which essentially adds clear: both just before the closing of the nav element.
/* For modern browsers */
.cf:before,
.cf:after {
content:"";
display:table;
}
.cf:after {
clear:both;
}
/* For IE 6/7 (trigger hasLayout) */
.cf {
zoom:1;
}
Because we’re using LESS for our CSS, applying the clearfix to our main-navigation class without modifying the markup is very easy.
.main-navigation {
.cf;
…
}
We’ll see more of this, as well as a description of how this works, in the section titled “Rounded Corners and Gradients” below.

Styling

All righty. By now, you’re probably as tired of looking at an unstyled menu as I am. To start, we’ll build what looks like a block wall, and then chisel a nice menu out of it. We won’t serve the block wall to antiquated browsers, but it’s a good start anyway.

Background Color and Borders

.main-navigation {
font-size: 0.8em;

ul, li, a {
…
}
ul {
background: #eee;
border: 1px solid #ddd;
}
li {
…
border-right: 1px solid #ddd;
}
li:last-child {
border-right: none;
}
a {
height: 35px;
line-height: 35px;
margin: 3px;
padding: 0 15px;
}
.children {
…
}
}
In the code above, the text was just too big, so we shrunk it with font-size: 0.8em. This property is set on the main-navigation class, so it applies throughout the navigation. The top-level unordered list has a border: 1px solid #ddd property to break it out from the page. Each list item element is given a border-right: 1px solid #ddd; to separate it from each other. The li:last-child selector targets the last list item element in the unordered list, removing the right border because no item follows it.
The links within the navigation are given a background color and some left and right padding to add distinction and increase their clickable area. We’re fixing the height and line-height, instead of using top and bottom padding, so that we can predict more accurately where the child-level menus will be positioned relative to their shared parent list item.
Navigation resembling a block wall

Navigation resembling a block wall

Rounded Corners and Gradients

.main-navigation {
…
text-shadow: 0 1px 1px #fff;

ul {
border: 1px solid #ddd;
.border-radius();
.linear-gradient();
}
…
}

.border-radius (@radius: 5px) {
border-radius: @radius;
}
.linear-gradient (@start: #fff, @end: #ddd, @percent: 100%) {
background: @start; /* Old */
background: -moz-linear-gradient(top, @start 0%, @end @percent); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,@start), color-stop(@percent,@end)); /* Chrome, Safari 4+ */
background: -webkit-linear-gradient(top, @start 0%,@end @percent); /* Chrome 10+, Safari 5.1+ */
background: -o-linear-gradient(top, @start 0%,@end @percent); /* Opera 11.10+ */
background: -ms-linear-gradient(top, @start 0%,@end @percent); /* IE 10+ */
background: linear-gradient(top, @start 0%,@end @percent); /* W3C */
}
Above, we have created two new classes, border-radius and linear-gradient.
The border-radius class is actually what LESS developers refer to as a parametric mixin. Essentially, it’s like a class, but you can pass variables to it in case the default value isn’t exactly what you want. In this case, if 5 pixels isn’t what you want, you could reference the mixin as .border-radius(10px), and then it would use 10px instead of the original 5px. With the border-radius property, you could also pass it something like .border-radius(5px 0 0 5px), and it would apply the 5-pixel rounding to only the top-left and bottom-left corners. For more information and possibilities on border-radius, see “Border-Radius: Create Rounded Corners With CSS” at CSS3.info.
Another parametric mixin is linear-gradient. But with LESS, you can add classes to other selectors and it will apply the same styles—thus negating the need to modify the markup just to add another class (and, by extension, its styles) to an element. Both of the classes I’ve created cover the possibilities of browser syntax. Currently, Webkit has two different syntaxes, because for some reason the browser makers decided to ignore the specification when first implementing it and made up their own syntax. With Chrome 10 and Safari 5.1, they went back to the specification, joining the other browsers, and made things a little easier for us. However, if you still care about the previous versions, you’ll need to add their crazy syntax as well. We’ve also added a white text-shadow to the text in the navigation to give it a slightly beveled look.
Navigation with a gradient and rounded corners

With the two classes applied, you can see the slight gradient and the rounded corners.
Some browsers do not support CSS3 gradients. Yes, I’m looking at you, Internet Explorer 6, 7, 8 and 9. If you want to use something other than the filter syntax for gradients, you’ll have to wait for version 10. In the meantime, either you could use the filter syntax for IE (see the “For Internet Explorer” section of “Cross-Browser CSS Gradient”) and put them in an IE-specific style sheet, or you could use an image gradient. You could also just leave them without the gradient, but that’s not the point here.

Parent-Level Hover States

.main-navigation {
…
li:hover {
a {
.linear-gradient(#dfdfdf, #c0bebe, 100%);
}
.children {
…
a {
background: none;
}
}
}
…
}
The code above will trigger the hover state for anchor elements when the user hovers over their parent list item, rather than hovering over the anchors themselves. This way is preferable so that the anchor element maintains its hover state when the user is mousing over the child-level menu as well. Doing it this way does, however, create the need to reset the background color of anchor elements within the child-level menus. That’s the part you see within the children selector.
Hovering over the parent-level links

Hovering over the parent-level links

Displaying the Children

Bringing the children back onto the screen is easy enough. But before we get carried away, we need to clear out a few styles that are applied to all unordered lists, list items and anchors.
.main-navigation {
…
.children {
background: #fff;
left: -999em;
position: absolute;

li, a {
float: none;
}
li {
border-right: none;
}
}
}
The code above changes the background of the child-level menu to white, instead of the light gradient that we used in the parent-level menu. The next couple of lines remove the left float from the list items and anchors. We’ve also gotten rid of the right border that separates the list items in the parent-level menu.

The Hovering Box

.main-navigation {
…
.children {
background: #fff;
.box-shadow();
left: -999em;
margin-left: -65px;
position: absolute;
top: 30px;
width: 130px;
…
}
}

…
.box-shadow (@x: 0, @y: 5px, @blur: 5px, @spread: -5px, @color: #000) {
-moz-box-shadow: @x @y @blur @spread @color;
-webkit-box-shadow: @x @y @blur @spread @color;
box-shadow: @x @y @blur @spread @color;
}
…
We’ve added another parametric mixin to the equation. This one produces the box shadow, with all of its parameters as variables, and with the browser prefixes. We’ve borrowed the styles from .children to make the box appear to hover over the parent menu. To center the child underneath the parent element, we’ve set the left position to 50%, and set the left margin to the negative value of half the width of the child. In this case, the child level menu is set to 130 pixels wide, so we’ve set the left margin to -65 pixels.
Navigation w/child reset to hover style

Navigation with the child reset to hover style

Child-Level Hovers

.main-navigation {
…
.children {
…
a {
.border-radius(3px);
height: 30px;
line-height: 30px;
margin: 3px;
}
a:hover {
background: #dff2ff;
}
}
}
We’re using the parametric mixin that we created for the border-radius for the links in the children as well. Adding a 3-pixel margin and 3-pixel border radius to all of the anchor elements within the child menu will accent the 5-pixel border radius of the menu well. We’ve also adjusted the height and line height a little, because they just seemed too high. Finally, we gave the list items a nice soft-blue background color on hover.
Navigation w/child menus and their hover state

Navigation with child menus and their hover state

Responding to Mobile Browsers and Size Constraints

A lot of screen sizes and browsers are out there. The iPhone has had two resolutions. Up to the 3GS model, it was 480 × 320; since the iPhone 4, it has been 960 × 640. Android browsers run from 480 × 320 to 854 × 480. Android also has a lot of browsers to choose from. There are the usual Firefox and Opera, as well as a ton of browsers by small start-ups. You can get Opera for the iPhone, but since you can’t make it the default browser, you’re pretty much stuck with Safari. Given this variety, we’ll have to make some adjustments if we want our navigation to be useful on all devices and in all browsers.

Fitting the Content

Accomplishing this part is easy, but doing it will probably require adjusting our styles. But that’s why we’re here, isn’t it?
Currently, when we open the navigation demo in iOS, it looks like this:
Original navigation in iOS

Original navigation in iOS
This might not look too bad on a giant screen, and it might even be usable on the iPad, but you would struggle to use it on a phone. Zooming in might make it easier, but that’s not ideal. Optimizing for the device is preferable, and forcing the browser to use the available space is simple.
<meta name="viewport" content="width=device-width">
This alone makes a huge difference in the way the browser renders the page. And while the menu is not the prettiest it’s ever been, it is a lot more functional.
Navigation on iOS with the viewport adjusted

Navigation on iOS with the viewport adjusted

Media Queries

We can use media queries to adjust the styles based on the media in the browser. In this case, we’ll use the width of the page to change the look and feel of the navigation to make it more suitable to the available space. In this case, we’ll make the menu items more button-like.
@media only screen and (max-width: 640px) {
.main-navigation {
ul {
border: none;
background: none;
.border-radius(0);
}
li {
border-right: none;
}
a {
border: 1px solid #ddd;
.border-radius();
font-size: 1.2em;
height: auto;
.linear-gradient();
line-height: 1em;
padding: 15px;
}
}
}
In the code above, we’ve used a media query to target situations in which the user is only looking at a screen and in which the width of the window is a maximum of 640 pixels. In this scenario, we’ve removed the border, background and border radius from the unordered list, and applied those styles to the anchors themselves. We’ve also increased the font size of the anchors, cleared the height and line height, and adjusted the padding of the links to increase the clickable area.
Navigation adjusted for mobile display

Navigation adjusted for mobile
As you can see, the links look much friendlier in a mobile browser. They are, however, only half functional, because touch devices don’t have a hover state. This means that if you have child-level menus, as we do here, you’ll have to figure out a way to display them as well. You could replace the hover state with a touch event of some kind, or expand the children out onto the page. That would greatly increase the size of the navigation, though. The following method might be best.

Replacing the Menu in Mobile Browsers With JavaScript

$(function() {
/* Get the window's width, and check whether it is narrower than 480 pixels */
var windowWidth = $(window).width();
if (windowWidth <= 480) {

/* Clone our navigation */
var mainNavigation = $('nav.main-navigation').clone();

/* Replace unordered list with a "select" element to be populated with options, and create a variable to select our new empty option menu */
$('nav.main-navigation').html('<select class="menu"></select>');
var selectMenu = $('select.menu');

/* Navigate our nav clone for information needed to populate options */
$(mainNavigation).children('ul').children('li').each(function() {

/* Get top-level link and text */
var href = $(this).children('a').attr('href');
var text = $(this).children('a').text();

/* Append this option to our "select" */
$(selectMenu).append('<option value="'+href+'">'+text+'</option>');

/* Check for "children" and navigate for more options if they exist */
if ($(this).children('ul').length > 0) {
$(this).children('ul').children('li').each(function() {

/* Get child-level link and text */
var href2 = $(this).children('a').attr('href');
var text2 = $(this).children('a').text();

/* Append this option to our "select" */
$(selectMenu).append('<option value="'+href2+'">--- '+text2+'</option>');
});
}
});
}

/* When our select menu is changed, change the window location to match the value of the selected option. */
$(selectMenu).change(function() {
location = this.options[this.selectedIndex].value;
});
});
To summarize, first we’re checking whether the window is less than or equal to 480 pixels. To ensure an accurate reading on mobile devices, you can use a meta tag to scale the viewport accordingly:
<meta name="viewport" content="width=device-width">
We populate the first variable, windowWidth, with the value of the window’s width as defined by the given device. We can use this value to then check whether the width is narrower than a particular value. We’ve chosen 480 pixels here because, while we might want to use media queries to adjust the menu below 640 pixels, at a certain point the viewport would be just too small to justify the menu taking up all that space.
We then use jQuery to create a clone of our menu that we can later crawl to create our options. After we’ve done that, it’s safe to replace the unordered list with the select element that we’ll be using and then select it with jQuery.
In the largest part of the code, we’re crawling through the clone of our navigation. The selector used, $(mainNavigation).children('ul').children('li'), ensures that we go through only the uppermost list elements first. This is key to creating the nested appearance of the select menu. With it, we select the “direct” child-level unordered list elements and then their “direct” child-level list elements, and then parse through them.
Inside each of these “direct” descendants, we get the value of the href attribute and the text of the link, and we store them in variables to be inserted in their respective options. This is implemented by appending <option value="'+href+'">'+text+'&kt;/option> to our new select list.
While we’re in the top-level list item elements, we can check whether any child-level menus need to be parsed. The statement if ($(this).children('ul').length > 0) checks whether the count of the selector is greater than 0. If it is, that means child-level items need to be added. We can use that same selector, with a slight addition, to go through these elements and add them to our select list, $(this).children('ul').children('li').each().
The same parsing method applies to these elements, although they use different variables to store the values of the anchor tags, so as not to create conflicts. We have also prefixed text to the menu labels at this level, --- , to differentiate them from the other items.
Parsing through the menu in this method (nested) will create the parent-child relationship you would expect.
After the menu is created, a little more JavaScript will enable the select list to serve as navigation.
$(selectMenu).change(function() {
location = this.options[this.selectedIndex].value;
});
When the select menu is changed, a new option is selected, and the window location is changed to reflect the value of the option. That value comes from the href of the original anchor element.
The result is like so:
screenshot

The select menu in a desktop browser
Select menu on Android and iPhone

The select menu in Android and iPhone browsers
Given the increased clickable area of the native controls, the select menu is obviously much more user-friendly on mobile.

Tuesday, March 27, 2012

Writing Unit Tests For WordPress Plugins


Writing Unit Tests For WordPress Plugins
When my WordPress plugin had only three users, it didn’t matter much if I broke it. By the time I reached 100,000 downloads, every new update made my palms sweat.
My first goal for the WordPress Editorial Calendar was to make it do anything useful. I was new to JavaScript and PHP and didn’t really know what I could pull off. In a few days I had a proof of concept. In a few more I had a working version and was asking friends to install it. The calendar worked… sort of.
I spent three times as much time fixing bugs as I did coding. Once the plugin worked, I wrote unit tests to make sure it kept working.
The unit tests for my calendar use QUnit, but they really use just three functions: test, expect and ok. This article shows you how to integrate unit tests into your WordPress plugin, where to write unit tests and how they can help you.

QUnit Basics

Unit tests follow a basic pattern: do something, then check the results. (“Is this variable 4 when it should be 5?” “Does this line of my table show up where it’s supposed to?”)
function myTest() {
test('My test run', function() {
expect(2);
ok(5 === 5, 'This test will always pass');
ok(5 === 6, 'This test will always fail');
});
}
This structure forces you to think of your code in simple units that return true or false. The test function starts a test run with two arguments: the title for this test run, and the function containing the tests. The expect function tells QUnit how many tests are in the run. If we call too few or too many, it causes an error.
The ok function performs the test of the expression. It takes two arguments: a boolean indicating whether the test was successful, and a message.
Test runs are added to a special list section, which shows the total number of tests, whether each test passed or failed, and how long the tests took.

A Real Unit Test

WordPress plugins complicate testing by using a combination of PHP and JavaScript. Even passing a simple value from PHP to JavaScript gets tricky.
The function below finds a WordPress preference with the get_option function and creates a JavaScript variable with the resulting value.
function getOption($myOption, $myVariable) {
if (get_option($myOption) != "") {
?><script type="text/javascript">
<?php echo($myVariable); ?> = <?php echo(get_option($myOption)); ?>;
<php
}
}
Now we’ll call it to get the name of the blog and set it to a variable named myBlogName.
getOption("blogname", "myBlogName");
Little helper functions like these glue your plugin together, but they always worry me. Did I access the JavaScript variable with the right name or did I mistype it? Did I use the same name twice? A simple unit test makes all of these worries go away.
function wpPrefTest() {
test('Get access to WordPress preferences', function() {
expect(1);
ok(myBlogName, 'The variable (myBlogName) should be available.');
});
}
This unit test checks whether the variable myBlogName exists. We could also look for a specific value or compare it to something else from the application.
Once you have this unit test, you’ll never need to worry about getting the blog’s name. It will always be there, and you’ll find out fast if you ever break it.

Integrating QUnit With WordPress

Testing in special development environments isn’t accurate. I wanted to add QUnit directly to my calendar, but I didn’t want to make the page’s size larger. The solution is a URL parameter and a little PHP to include QUnit only when I need it:
wp_enqueue_script( "qunit", path_join(WP_PLUGIN_URL, basename( dirname( __FILE__ ) )."/lib/qunit.js"), array( 'jquery' ) );
wp_enqueue_script( "edcal-test", path_join(WP_PLUGIN_URL, basename( dirname( __FILE__ ) )."/edcal_test.js"), array( 'jquery' ) );
This tells WordPress to include the QUnit JavaScript and my unit tests from edcal_test.js. I could have just embedded the script’s reference directly on my page, but I might have run into trouble if other plugins on the same page use QUnit.
You can see the full source code here.
The next step was to make sure that these scripts load only when I need them. To do this, I wrapped the code in a check for a URL parameter:
if ($_GET['qunit']) {
wp_enqueue_script( "qunit", path_join(WP_PLUGIN_URL, basename( dirname( __FILE__ ) )."/lib/qunit.js"), array( 'jquery' ) );
wp_enqueue_script( "edcal-test", path_join(WP_PLUGIN_URL, basename( dirname( __FILE__ ) )."/edcal_test.js"), array( 'jquery' ) );
}
This loads the scripts only if I’m running unit tests, and everything else in the plugin stays the same. You can run the unit tests at any time just by adding &qunit=true to the end of the URL. That’s a good thing because my unit tests actually change what’s going on in the blog.
You can run the Editorial Calendar’s unit tests in your browser right now. Scroll down to see the unit test results at the bottom of the page.
The PHP makes sure that my scripts get to the browser. The last step is to call them from my JavaScript. Once again, I want to call them only if we’re in unit test mode. So, I add a small function to get the parameters from the URL:
getUrlVars: function() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
And then I call my unit tests if the QUnit parameter is there:
jQuery(document).ready(function() {
if (edcal.getUrlVars().qunit) {
edcal_test.runTests();
}
});
This ensures that we call the unit tests only if they’re available.
The last step is to set up a space for the unit test’s output. QUnit writes its test results into specially designated tags on your HTML page. You could embed these tags directly in your HTML output, but because they need to be there only when QUnit is active, I create the HTML in JavaScript instead.
jQuery('head').append('<link>');
css = jQuery('head').children(':last');
css.attr({
rel: 'stylesheet',
type: 'text/css',
href: '../wp-content/plugins/edcal/lib/qunit.css'
});

jQuery('#wpbody-content .wrap').append('<div id="edcal-qunit"></div>');

jQuery('#edcal-qunit').append(
'<h1 id="qunit-header">WordPress Editorial Calendar Unit Tests</h1>' +
'<h2 id="qunit-banner"></h2>' +
'<div id="qunit-testrunner-toolbar"></div>' +
'<h2 id="qunit-userAgent"></h2>' +
'<ol id="qunit-tests"></ol>' +
'<div id="qunit-fixture">test markup</div>');
QUnit needs a list tag, a couple of divs and a style sheet.

Now we’re ready to write our first test.

The First Unit Test

The first calendar unit tests scroll the calendar up and down and make sure we see the correct number of days.
moveTests: function() {
var curSunday = edcal.nextStartOfWeek(Date.today()).add(-1).weeks();
edcal.moveTo(Date.today());

test('Move to today and check visible dates', function() {
expect(2);
ok(edcal_test.getFirstDate().equals(curSunday.clone()),
'firstDate should match ' + curSunday);
ok(edcal_test.getLastDate().equals(
curSunday.clone().add(edcal.weeksPref).weeks().add(-1).days()),
'lastDate should match ' + curSunday);
});
}
Our first test moves the calendar to today and checks to see if the first and last days are what we expect. We set up a variable, move the calendar and start the test by calling the test function.

In this case we want to make sure the dates are correct, so we compare the date from the calendar to the one we expect and then pass the result to the ok function. The test succeeds if they match and fails if they don’t.
This test may seem simple, but a lot is going on under the hood. We’re testing date handling, drawing and the fundamental arithmetic of the calendar.
Unit tests can do anything. The WordPress Editorial Calendar unit tests automate the plugin like a robot. They cover everything a user could do with the calendar.

What To Unit Test

I write a lot more unit tests for JavaScript than I do for compiled languages. In Java and C++, the compiler catches many of my mistakes, whereas JavaScript lets you pass a string when you meant to pass a number and lets you call a function with two arguments when it needs three.
Here’s the basic list of areas I test in JavaScript applications:
  • Tests that make sure the program does what it is meant to do

    These tests ensure the basic functionality keeps working; they do not test interactions. (The calendar lets you drag and drop posts, but writing unit tests for dragging and dropping wouldn’t make sense; instead, we would focus on what happens after the drop event.)
  • Tests that make sure the program doesn’t do what it’s not meant to do

    These tests ensure the program fails properly when it gets garbage.
  • A unit test for every major bug I’ve found

    These tests ensure that none of these bugs creep back in.
APIs and other clear boundaries in the code lend themselves well to unit tests, as do utility functions that you call from many places in the application. With the calendar, this means testing calendar movements and testing how we create and modify posts in WordPress, like this:
  1. Move the calendar and check the dates;
  2. Create a post and make sure it was created properly;
  3. Edit the post we just created and make sure it saves properly;
  4. Move the post and make sure it shows up at the correct date;
  5. Move the post from two places at the same time and make sure we get the proper warning message;
  6. Delete the post from the server and make sure it isn’t there anymore.
The penultimate test covers an error condition in which two people move the same post at the same time. Unit tests work well for this kind of error, because the error type is difficult to test and manual testing is less likely to uncover problems.

For your own application, you should have at least one unit test for every data-changing operation that users can perform. I like to add them for all of the places where a user can get data, too. It might sound like a lot of work, but you can cut down on it by writing single tests that cover multiple areas.

Asynchronous Unit Tests

Many of these combination unit tests make AJAX calls. QUnit provides a special function for handling AJAX called asyncTest. This function works just like test, but it pauses the test run at the end of the function. The QUnit framework waits until your AJAX call completes and you call the start function before restarting the test run.
The asyncTest function handles all of the tests that edit posts from the calendar, including deleting the post at the end:
asyncTest('Delete the post created for testing', function() {
expect(1);

edcal.deletePost(edcal_test.post.id, function(res)
{
equals(jQuery('#post-' + res.post.id).length, 0,
'The post should now be deleted from the calendar.');
start();
});
});
When you restart the test framework you can call more tests. Calling the next test function at the end of the previous one chains them together, and it supports calling all of your tests with just a call to the first function.
These tests, which call AJAX, ensure that the integration between the JavaScript on the client side and the PHP on the back end works properly.

That’s Not a Unit Test

When I first learned to write unit tests in C++ the rule was this: a single test should only call code in a single module or CPP file. That is, a unit test should test one unit of code.
Changing posts from unit tests violates that rule. Instead of just testing JavaScript, I’m really testing JavaScript, PHP, WordPress itself and MySQL all at once. That makes it an automated integration test.
Integration tests aren’t traditional unit tests, but they work well for WordPress plugins. When I create a post, I’ll know that the AJAX code in my plugin works as well as the JavaScript code. Covering a larger portion of the application with fewer tests makes it easier to focus on what I should be testing.

What Not To Unit Test

You could write unit tests forever, but some are more useful than others. Here are some guidelines.
  • Don’t unit test the UI.

    The test has to run by itself. It can’t wait for you to click a button or look at something to make sure it appears correctly.
  • Don’t unit test performance.

    Tests take a variable amount of time on different machines and browsers. Don’t write unit tests that depend on a function being returned in a set amount of time.
  • Don’t unit test code from other projects.

    Adding unit tests for WordPress or a jQuery plugin you depend on might be tempting, but it rarely pays off. If you want to contribute unit tests to WordPress.org that’s great, but your unit tests should check that your plugin works.
The Editorial Calendar has 26 unit tests, at about 3,500 lines of code. That may not sound like much, but they’ve saved many of my releases.

Unit Tests Saved My Butt

I didn’t add unit tests until the thirteenth release of my plugin. By then, the calendar had a couple of hundred users and was growing fast. My plugin was working, and I was getting close to release 1.0.
Instead of adding new features, I took in a new framework, added special code to load it, wrote 381 lines of unit tests and integrated all of this into the plugin. It seems like a lot of work, but it saved my butt.
Right before a release, I wrote some harmless-looking PHP code like the following to get the JSON data that represented a set of posts to show up in the calendar:
function edcal_postJSON($post) {
setup_postdata($post);
?>
{
"date" : "<?php the_time('d') ?><?php the_time('m') ?><?php the_time('Y') ?>",
"title" : <?php echo($this->edcal_json_encode(get_the_title())); ?>,
"author" : <?php echo($this->edcal_json_encode(get_the_author())); ?>
},
<?php
}

function edcal_posts() {
header("Content-Type: application/json");

global $post;
$args = array(
'posts_per_page' => -1,
'post_status' => "publish&future&draft",
'post_parent' => null // any parent
);

$myposts = query_posts($args);

?>[
<?php
$size = sizeof($myposts);
for($i = 0; $i < $size; $i++) {
$post = $myposts[$i];
edcal_postJSON($post, $i < $size - 1);
}
?> ]
<?php
}
I ran the code and everything worked. I was about to release the new version but ran my unit tests first to make sure. They failed. Can you spot the bug? I didn’t.
I was returning a JSON array, but the last item in the array had a trailing comma. That’s invalid JSON. Firefox accepts it, but Safari, Chrome and IE don’t. I almost shipped a broken plugin to over half of my users.
Now I run the unit tests on all major browsers whenever I release a new version. Any time WordPress releases a new version, I run the unit tests. WordPress 3.3 broke the calendar — and I found out exactly why in 15 seconds.

Popular Plugins Are Stable Plugins

Most WordPress plugins are free and open source, but free doesn’t always mean cheap. The total cost of ownership of unstable plugins is more than people would pay. That’s a fancy way of saying that users will run from your plugin if it’s a bug fest.
My plugin became popular because of its features, but stability kept it popular. People remember one buggy release for a long time. If the Editorial Calendar deletes or corrupts posts from just one blog, thousands of people would stop using it. And they’d be justified.
Unit tests add the stability you need to support the multitude of browsers, mobile devices and dark corners involved in any JavaScript application. They’re easy to write, and they pay you back: because you find the bugs, and your users don’t.

Techniques For Overcoming Poor CSS Support In Email



Techniques For Overcoming Poor CSS Support In Email


Designing and developing emails can be challenging, especially if you start doing it after years of designing and developing websites. Unlike most Web browsers, email clients have not yet united in support of HTML email standards, resulting in poor CSS support for email.
Inconsistent support for images in email clients has thus motivated us to experiment in a code editor and to develop the following techniques.

Technique 1: HTML Gradients

Creating gradients for the Web is very simple with repeating background images and tools that produce cross-browser-compliant code, such as Ultimate CSS Gradient Generator. A gradient for email requires a much different approach, due to the lack of support for background images in some email clients.
Using gradients in email is possible without repeating background images or CSS3. It can be achieved entirely in HTML with pixel planning, table-cell background colors and appropriate cell widths and heights.

How to Begin an Email Template With Gradients

Because designing and developing for email requires an awareness of the limitations of email clients, as opposed to standards for Web browsers, we should start with a review of CSS support in email.
Emails are coded using tables, so we have to create design sketches and Photoshop mock-ups with table-based layouts in mind. Keep it simple, and have a clear idea of where to position the gradients and how they will behave (say, if we want a gradient to expand horizontally to fit the viewport’s width).

How Gradients for the Header, Box Shadow And Footer Differ

  1. The header gradient will expand horizontally on either side of the header image according to the browser or device’s width. So, if the viewport’s width is wider than the width of the header image, the gradient will fill the extra space. Using percentage widths of 33%, 34% and 33% for three columns makes this possible.
  2. The box-shadow gradient will have a fixed width and a flexible height depending on the content’s height, which will vary from email to email.
  3. Similar to the header gradient, the footer gradient will also expand horizontally according the browser or device’s width, but it will not have an image in the center.
screenshot
Behaviors of the header, box-shadow and footer gradients.

Plan Pixel by Pixel: Sample Colors, Record Colors and Note Number of Repeating Colors

Colors need to be sampled and recorded to recreate the gradient in HTML. Because the HTML header gradient will appear on either side of the header image, the HTML colors will need to match the colors in the header image. Sample colors from the actual optimized image, not the PSD; optimizing an image for the Web and reducing the file’s size using a tool like ImageOptim could change the color values slightly from the PSD.
The header image is the maximum recommended width of the email (600 pixels wide) by 120 pixels high. Open the optimized header image in Photoshop and zoom in 3200%. Use the Eyedropper tool to sample the color values for each pixel from top to bottom. Record the color values in a text editor, and note the number of pixels if color values repeat. Sample colors directly from the PSD for the box-shadow and footer gradients, since they don’t need to match any optimized images. Record the footer gradient colors just as you did the header gradient.
Screenshot
Zoom in, gather and record color values using the Color Picker tool in Photoshop.

Curveball Corners

The box-shadow gradient isn’t all gradient. The gradient lies between the four corners, which can also be recreated in HTML. Use the Color Picker to determine where the gradient ends and the corner begins. Sample and record colors as you did for the gradient portion of the box shadow. Use a spreadsheet for the corner portion of the box shadow to record color values and the pixel position. Sampling and recording only one corner and one side of the gradient is necessary because the color values are the same for all four.
screenshot
Record the pixel position and color values for one corner in a spreadsheet. Use this data to create all corners in HTML by flipping the order of the color values.
Save all files with the color data for later reference when coding.

Temporary Tricks to Make Coding Easier

Add temporary cell padding and a width of 100% to the table to make cells easier to select in the design view in Dreamweaver. Add background colors to distinguish corners for easier merging.
screenshot
Left: Temporary colors and padding distinguish corners and cells for easier coding. Right: Add color values and merge center cells.

How to Code the HTML Gradients

Copy and paste the recorded color values into the <tr> tags as background colors. Add heights to the <td> tags by referring to the repeating pixel numbers, and then merge the center cells from the end of the gradient up. This merged <td> cell is the place to add the header image.
<tr bgcolor="#525252">
<td height="2" width="33%"></td>
<td rowspan="95" width="34%">Header image will go here</td>
<td width="33%"></td>
</tr>
<tr bgcolor="#515151">
<td height="2"></td>
<td></td>
</tr>
<tr bgcolor="#505151">
<td height="1"></td>
<td></td>
</tr>
<tr bgcolor="#505050">
<td height="2"></td>
<td></td>
</tr>
<tr bgcolor="#4f4f4f">
<td height="2"></td>
<td></td>
</tr>
To code the HTML corners, refer back to the spreadsheet for the values of the corner colors. Copy and paste them into the appropriate <tr> tags. The background colors from one corner can be applied to all corners by flipping the order of the color values vertically and/or horizontally.
Fixed heights and widths will keep the cells from expanding. Apply cell heights and widths only to those cells that need defining. For example, in the box-shadow gradient, add heights to the cells of the first column only, excluding the one center cell that represents the gradient. This will allow the gradient to expand vertically depending on the content’s height. Add widths to all cells of the first row only. The middle cell of the first row needs to be wider in order to hold the nested table of content.
Once all heights, widths and colors have been added, remove the temporary cell padding, 100% table width and non-breaking spaces.
screenshot
The design view in Dreamweaver, showing the main table complete with header and footer gradients.
Here are some pros and cons to the HTML gradient technique.
Pros
The results are clear. This technique renders consistently well for the vast majority of email clients without relying on images or background images, which have inconsistent CSS support. This means that more people will be able to view the design as intended, without having to change their email settings to display images. It also gives the designer more creative freedom and makes consistent branding possible where gradients exist. And remember, not all gradients have to be as complex and time-consuming as the header and box-shadow gradients in this article. These are included to show different examples and to demonstrate how they can be accomplished. The footer gradient covered here is fairly quick and easy.
Cons
This technique does have potential drawbacks. It can be labor-intensive and require additional code, which could increase the file’s size; this will depend on the number of colors in the gradient itself and the number of gradients in the email template. HTML gradients might not be practical for everyone; an alternative technique that uses background images is worth checking out.

Technique 2: Plan Padding As Rows And Columns

When it comes to padding for email, planning and coding the padding using rows and columns with widths and heights is key. This technique renders better and more consistently in email clients than inline margins, CSS padding or cell padding.

Drag and Count

In Photoshop, make sure to turn on the rulers, which makes adding guides possible. Drag guides vertically and horizontally over the PSD mock-up to define sections for content, images, padding, etc. Once the columns and rows are clearly defined, count them and insert the table accordingly.
screenshot
Use guides in Photoshop to figure out the number of columns and rows for the content table.

Merge With Care and Check Your Wide Load

Use temporary cell padding to make merging easier. Merge cells to create distinct sections as defined by the PSD guides and to eliminate extra code where possible. Keep track of cell widths after each merge so that all cells, merged or not, add up to the total fixed width of the table. Remember to remove the temporary cell padding when the table is complete.
screenshot
Four tables merged, with appropriate cell widths and heights applied.

How to Avoid Unintended Extra Cell Padding

Eliminating white space between <td> tags is important. Some email clients create additional padding from white space, which will ruin the gradient by blowing up the cells’ heights. Non-breaking spaces should also be avoided for similar reasons across all email clients.
Remember to paste only HTML code into the HTML view of a WYSIWYG window. Don’t paste HTML code into the visual view of a WYSIWYG window. The WYSIWYG editor will add unwanted code to HTML, such as non-breaking spaces, which will cause inaccurate results, ruins margins, etc. It can also drive a developer who is trying to debug the code insane.

Tools to Test Email Templates

Check the HTML template throughout the coding process locally in a browser. Another helpful resource is Fractal, which validates HTML emails across all major clients and fixes known email quirks. The last step is to test for cross-client compatibility. Litmus provides email previews across 30+ email clients, spam filter tests and email analytics. I use Carrier Pigeon, which uses a Litmus rendering feature.

Final Result Among Different Email Clients

HTML gradients and padding render consistently across the following email clients and browsers:
  • AOL Mail (Internet Explorer and Firefox);
  • Apple Mail 4;
  • Gmail (Internet Explorer and Firefox);
  • Hotmail (Internet Explorer and Firefox);
  • Lotus Notes (8 and 8.5);
  • Me.com (Firefox);
  • Outlook (2000, 2002/XP, 2003, 2007, 2010);
  • Thunderbird (2.0 and 3.0);
  • Yahoo Mail (Internet Explorer and Firefox).
Lotus Notes (6.5 and 7) is the only email client that does not display gradients correctly.
screenshot

Stop Designing Pages And Start Designing Flows

Stop Designing Pages And Start Designing Flows

For designers, it’s easy to jump right into the design phase of a website before giving the user experience the consideration it deserves. Too often, we prematurely turn our focus to page design and information architecture, when we should focus on the user flows that need to be supported by our designs. It’s time to make the user flows a bigger priority in our design process.
Design flows that are tied to clear objectives allow us to create a positive user experience and a valuable one for the business we’re working for. In this article, we’ll show you how spending more time up front designing user flows leads to better results for both the user and business. Then we’ll look in depth at a common flow for e-commerce websites (the customer acquisition funnel), as well as provide tips on optimizing it to create a complete customer experience.

Start With The User

When starting a new Web design project, we’re often handed a design brief, branding standards, high-level project goals, as well as feature and functionality requirements. Unfortunately, these documents typically amount to little more than the technical specifications of the project, with almost no thought given to how exactly the website will fulfill the multiple user objectives that lead to successful interactions.
Popular user flows for e-commerce and membership websites

Two examples of popular user flows for e-commerce and subscription websites.
If you start with a detailed look at the objectives of the user and the business, you would be able to sketch out the various flows that need to be designed in order to achieve both parties’ goals. User objectives could range from finding a fact to replacing a product to learning a new skill to buying a gift for someone. Business objectives could be getting a lead, a like, a subscriber, a buyer, a download or a phone call. Identifying each user and business objective is the first step to creating design flows that meet all of them.

Map User Flows Into Conversion Funnels

Not all website visitors are created equal. Users come from different sources, with varying levels of knowledge and engagement, and with different goals. It’s up to you as a user experience designer to map those in-bound user flows to conversion funnels that provide value to the user as well as the business.
You should prioritize the flows and focus your effort on the few that will impact the most users and have the greatest gain. Custom flows allow you to architect experiences according to traffic source or visitor type and enable you to set the experiential pace, build user confidence and get buy-in on the way to the ultimate conversion.

Typical User Flows

Some typical user flows are:
  • Paid advertising

    A user coming from a banner or Google AdWord ad.
  • Social media

    A user coming from a friend’s post on a social network.
  • Email

    A user coming from an email newsletter or referral invitation.
  • Organic search

    A user coming from a deep link that was surfaced by a search.
  • Press or news item

    A user coming from a mention in the news or a blog post.
Each of these visitors has their own needs, expectations and level of knowledge, and they need to be treated accordingly.

Diving Into Funnels: A Closer Look At Customer Acquisition

Typical conversion funnels for e-commerce websites

E-commerce websites typically have many different conversion funnels.
Let’s look at a critical flow for many websites — paid online customer acquisition — and break down its various elements. For this example, we’ll examine the experience flow from new visitor to email subscriber to purchaser.
Consider a company that uses display advertising to generate new customers for its business.

Display Media

With display advertising, it all starts with the banner. The design of the banner needs to achieve one precious goal: get a click from the right person. Here are some key questions to answer when designing the ads that represent the very front of your user flow:
  • What type of user am I targeting?
  • Are they actively seeking a solution to a problem, or are they casually browsing?
  • What problem are they trying to solve?
  • How can I best capture the user’s attention?
  • How do I relate to the user?
  • Is there a message that will resonate with the user?
  • Is there a pain point that my product or website alleviates for the user?
  • How can I articulate this solution clearly and quickly?
  • What compelling calls to action will get our target user to click?
Your ads should address these main motivations and provide a compelling hook to get that all-important click. Up-front research and real-world testing will help to optimize the experience. Using this model, ReTargeter improved its banner click-through rate by four times. Its blog post lays out exactly how it achieved this success.

The Landing Page

The point when the user hits the landing page is when the user flow work really begins. Because these users are coming from a low-information source (such as a banner, as opposed to an in-depth blog post), you must design a flow that fills in the gaps of information by providing the user with the data that they need to be converted.
In our example, the user will hopefully be converted to an email subscriber; but depending on the business, the conversion could be to create an account, download a white paper or make a purchase. Whatever the conversion goal for the business, the key is to give the user a reason to keep moving through the flow, down the funnel.
Use the following methods to keep the user moving down the funnel:
  • Build user confidence by clearly articulating key benefits, backed by easy-to-digest proof points.
  • Streamline the content and design to focus on a clear call to action (in this example, to sign up for an email newsletter).
  • Remove friction at every step. Ask for the minimum amount of information, and reduce the number of fields, extra clicks and page-loading time.
  • Create an enticing hook, an itch that can only be scratched by completing the registration step.
KISSmetrics’ “Anatomy of a Perfect Landing Page” details the design, UI and copy elements that can help you meet your users’ need and drive conversions for your business.

Stacking Flows For A Complete User Experience Life Cycle

While viewing a funnel as something like Click on banner ad → Land on Web page → Register email is easy, designing and building stacked flows that drive the business’ ultimate objectives takes a bit more thought. In our example, we’ve successfully gained an email subscriber from the banner ad campaign, but the real business objective is to generate revenue through new purchases.
Treating the email subscriber flow and the e-commerce purchasing flow as two separate conversion funnels is an easy trap. In reality, the experiences are connected, and by looking at them as stacked flows, we can create a more cohesive interaction, one that drives optimal results for the business.
In our example, this stack is made up of the customer acquisition funnel and the customer relationship management (CRM) flow.
Stacked funnels create a complete interaction life cycle

Stacking funnels creates a cohesive user experience life cycle.
When designing this flow, you need to consider what the biggest levers are for converting the subscriber into a buyer. Many of the earlier principles apply, but this time you have more touch points to consider and leverage.
In this flow, you need to look at all elements of your CRM strategy and the purchase flow of your website, including:
  • Email communication back to the subscriber,
  • Pages that the subscriber lands on when returning to the website,
  • The flow from internal content pages to check-out.
Here are a few key considerations when designing the flow from subscriber to purchaser:
  • Tell a visual story that the subscriber can identify with and wants to be a part of.
  • Ensure that your emails reinforce the story, and give proof points to remind users why they subscribed.
  • Include compelling calls to action to give the subscriber an opportunity to relate to and be a part of the story.
  • Include prominent calls to action and easy, direct paths to the check-out process from the website’s internal content pages and blog posts. These validate the user’s hope about their role in the story.
  • Make the check-out process as frictionless as possible, and reinforce confidence along the way to help the buyer commit to being a part of it.
By considering how the two flows interact, you can create a seamless experience that builds confidence and deepens the user’s connection to your website, leading to the ultimate purchase conversion. Equally important, this flow also increases customer satisfaction because the stacked funnels keep the user experience smooth and on track to meeting their needs, with little confusion or ambiguity.

Putting Flow Design To Work For You

Whether you’re mapping out a brand new website or looking to optimize an existing user experience, flow design will keep you out of the trap of designing individual pages and interactions and instead focus you on fulfilling users’ needs. By prioritizing your user flows and focusing on the ones that drive the most value to the most users and to the business, you can make the greatest impact with your initial flow design.
When considering user flows, think past the first conversion, and design for the ultimate conversion, which might lie a few steps behind. This is particularly important with any type of commerce-driven business, for which the first conversion is often just a prelude to the primary revenue event. By stacking these complementary funnels, you create a more cohesive user experience that drives better results for both the user and your business.
So, the next time you’re asked to create a new design, step back and ask yourself and your team what user flows you are trying to create through the website, and let that insight drive the design process.
(al)

Design Features for the Monarch Butterfly Life Cycle



Design Features for the Monarch Butterfly Life Cycle

Perhaps the most familiar butterfly to nature lovers around the world is the orange-winged monarch butterfly. This beautiful creature reigns supreme because: (1) it lives longer, (2) travels farther, (3) has a wider distribution over the earth, and (4) has a more beautiful pupa than any other butterfly.

Cycle

The four developmental stages in the life cycle of the monarch butterfly are the egg, the caterpillar (larva), the pupa (chrysalis), and finally, the emergence of one of the most beautiful creatures on Earth, the butterfly. Female butterflies begin the next cycle when one small, pin head sized, white egg is laid underneath the leaf of a milkweed plant -- a plant which is poisonous to most creatures. Inside the egg the caterpillar begins to develop, drawing upon the yolk material inside the egg for nutrition. After three to five days, this caterpillar eats a hole in the egg case and emerges onto the leaf surface.

At this stage, the caterpillar is about 0.1 inch long and weighs about 0.55 milligrams. Nine chocolate-colored rings encircle its grayish body; it has a black head, three pairs of front true legs with claws, and five pairs of prolegs extending backwards, adding a unique and functional form to the body. It also has a mouth, stomach, and silk gland, among other parts characteristic of a full-grown caterpillar. The caterpillar usually eats more of its egg case, and then the milkweed leaf. Rapid growth leads to four or five molts -- the shedding of its external skin.

In about 20 days, the butterfly's weight has increased to 1.5 grams, or 2700 times its weight when it emerged from the egg. At about two inches long, with yellow, white, and black stripes on its body, it stops eating and spins a white silk pad on a stiff object, attaching itself by its two rear prolegs to the silk pad. It then hangs head down in a J-shape position in a seemingly inactive stage for approximately 12 hours.

At the end of this period in its cycle, the caterpillar begins to convulse in rhythmic jerks, breaking off its outer skin. During this stage in its development, its 16 legs and head capsule (with 6 eye lenses) are shed in about 60 seconds, giving rise to a pupa, or chrysalis, about 1 inch long and about 0.4 inches in diameter. The chrysalis, at this point, is jade green, with about 24 metallic appearing gold spots (the gold crown) surrounding half of its upper abdomen. There are 12 metallic-like gold spots on the remaining parts of the chrysalis, all of which are necessary for the normal development of the butterfly.

The caterpillar enters the chrysalis stage without vision, because the head capsule was discarded with its six simple eyes, so it can now only distinguish light from darkness. The inside portion of the chrysalis, below the gold crown, turns to a jade green liquid within the first 16 hours, as the caterpillar's stomach, intestines, and most all of the other internal parts disintegrate. In the center portion of the gold crown area is a red heart, about 0.1 inches in diameter, surrounded by a yellowish substance. This heart pulsates at about 40 to 60 beats per minute. The thin outer chrysalis layer contains cells which later develop into the wings of the butterfly. One can see the outline of the beginning wings through the somewhat transparent outer shell. This thin outer shell has a pattern of lines which mark the position of the future butterfly proboscis, first and second pair of legs, and two antennae. These lines are clearly seen from the outside, but they never really become part of the butterfly, remaining, instead, on the transparent shell after the emergence of the butterfly, and are apparently used only as a guide for building the butterfly proboscis, legs, and antennae. The proboscis is the tubular sucking organ, used to suck sweet nectar from the flowers it feeds upon.

After 8 to 14 days, the caterpillar emerges from the chrysalis in as rapidly as from 15 to 30 seconds. It extends its wings by pumping fluid from its abdomen into the wing veins, and is ready to fly in about 15 minutes. Once the wings dry, which takes approximately 2 hours, the butterfly is full grown, having been transformed into an entirely different creature from the caterpillar. It now has only six legs and four beautiful orange wings, which are surrounded by a narrow black border studded with white spots. The wingspread at the two forward wings is about 4 inches. Its body is about 1.3 inches long, 0.15 inches wide, and weighs about 0.41 grams. It has two compound eyes, each having 6000 lenses which are sensitive to all the colors of the rainbow, and even to ultraviolet light. It can see objects as small as a pin-head, because the female monarch butterfly won't lay an egg on a milkweed leaf if it sees another egg on it. It has a brain that can decipher 72,000 nerve fiber electrical pulses coming from the two eyes, into meaningful images. The very idea that such an intricate and complex system could have developed by natural selection or any other evolutionary mechanism is absurd.

Migration

The monarch butterfly can fly thousands of miles to its wintering location, and some tagged monarchs have been known to travel from Canada to the Neovolcanic Mountains of Mexico, a distance of 3000 miles. During autumn, the Eastern population of monarch butterflies (east of the Rocky Mountains) migrates southwest for two months to the Neovolcanic Mountains of Mexico. These monarchs cluster in trees from 9000 to 11,000 feet elevation for approximately 4 months, in freezing temperatures, from November to March. This wintering period allows them to hibernate, thus conserving their energy. During this interval they eat and drink little, thus enabling some of them to live as long as one year. During the spring, the eastern population of monarch butterflies migrate from Mexico northeastward towards the U.S. Some return the long distances to where they were born, while others fly only part of the distance to Texas or the lower southern states (first-generation monarchs), living and dying in approximately six weeks. The eggs that have been laid hatch into a second generation which continue the flight farther north, taking as many as four generations to fly as far north as Ontario, Canada. The last generation does not develop its reproductive organs, and therefore begins its autumn migration back to Mexico. When the female lays her last egg, her process of dying begins, so those in the 5th generation sustain the greatest longevity. The monarch butterflies are the only insects on Earth to migrate annually over continental distances, and it is estimated that over 300 million of these fantastic creatures migrate to Mexico every year. Their navigational systems are extremely complex to direct them as far as 3000 miles to a wintering site they have never seen, and then to guide them in the spring on their northeast travel to different parts of the U.S. and Canada. Evolutionism provides no believable explanation for such remarkable abilities.

Monarchs west of the Rocky Mountains, considered those of the western population, travel to the west coast from Baja California to north of San Francisco, while others of them come from British Columbia in the autumn to winter in California -- these, again, with life spans of approximately only six weeks.[1]

Design

Two polar-opposite views are put forward to explain the order in the universe: the "chance" theory and the "design" theory of creation. The chance theory grew out of Greek philosophy as the Epicurean Hypothesis in about 400 B.C.[2] It received its strongest support from Darwin's theory of evolution, and is acclaimed today by materialists such as David L. Hull, who said: "Darwin's theory was one of the chief instruments in the final trivializaton of teleology."[3]

Design theory had its foundation in Scripture (Nehemiah 9:6), and has been championed by many scholars over time, including William Paley,[4] with his "Natural Theology" in the 18th century.

At least eight categories of design are put forward as evidence for a designer: order, purpose, simplicity, complexity, beauty, sense and cognition, information, and cosmic constants. "The design argument in analogy form is empirical or a posteriori. It makes an appeal to evidence in the form of generalizations."[5] An empirically based design statement by itself is unable to "prove" a designed universe with certainty.[6] But, as Denton says, "It is the sheer universality of perfection, the fact that everywhere we look, to whatever depth we look, we find an elegance and ingenuity of an absolutely transcending quality, which so mitigates against the idea of chance."[7]

Conclusion

When one examines the life and migration cycles of the monarch butterfly, it is easy to see design features which point back to a Designer. There is inexorable order in the repeatable progress of developmental stages. An incredible plan unfolds in the transforming pupal stage, through larval disintegration and reintegration to the miracle and beauty of a winged insect. Simplicity in feeding, complexity in navigation, beauty in coloration all speak of incredibly packed information in its genetic message. By whatever means it is drawn or directed to make such Herculean flights to its wintering grounds, there must be some type of implanted foreknowledge in its very being that makes it all possible.

-- References --

  1. Fred A. Urquhart, The Monarch Butterfly: International Traveler, (Chicago, Nelson-Hall Inc., Publishers, 1987), Excerpts made for natural history and migration discussion.
  2. James E. Horigan, Chance or Design (New York, Philosophical Library, 1979) p. 30.
  3. David L. Hull, Darwin and His Critics (Cambridge, MA, Harvard University Press, 1973) p. 57
  4. William Paley, Natural Theology, From a Late London Edition (New York, American Tract Society, n.d.).
  5. J. P. Moreland, The Secular City, A Defense of Christianity (Grand Rapids, MI, Baker Book House, 1987) pp. 44-56.
  6. James E. Horigan, p. 50.

Faceted Overload: Simplifying the Sidebar Navigation

Faceted Overload: Simplifying the Sidebar Navigation

the benefit of using a faceted sidebar navigation on your website is that you aren’t vertically constrained by space. You can list as many links in the sidebar as you need. However, this known benefit also has an unknown downside. Listing too many links in your sidebar can lead to faceted overload. This is when the faceted navigation extends below the fold, and overwhelms users with links on the side of the page. This faceted overload makes information harder to find, slows users down and can clutter the page.

The reason information is harder to find with an overloaded sidebar is because part of the navigation lies below the fold. This means the entire navigation is not visible to users at once. They have to scroll down to see the rest. And most of them won’t do this unless there’s a reason to.
If the user hasn’t found what they’re looking for in the navigation above the fold, they might scroll down to look for it below the fold. However, that’s only if they have an idea of what they’re looking for. If they don’t have a target in mind, they’ll keep most of their attention on links above the fold and ignore the ones below. This can lead to users missing links they might need.
Another problem for a user who is looking for a below the fold link is that they have to spend time and effort scanning through all the links above the fold before they can get to the links below the fold. Users shouldn’t have to waste time and effort looking through the links they don’t need to get to the links they do need. Finding the link they need should happen in seconds, not minutes.
A faceted overload can also lead to slower user engagement or none at all. The more links you display to users, the longer it’ll take for them to make up their mind. They not only have to read through more stuff, but they also have to decide where to go through the process of elimination. In order to say yes to one link, they have to say no to all the other links on the page. This means they have to look and consider everything. And a full-page of links is too much to consider.

Showing the Top-Level Link First

The goods news is that there’s a way you can keep all the links in your sidebar navigation while minimizing the user’s workload. By applying faceted minimization you can display your navigation above the fold, and allow users to bypass the links they don’t need. This will make your page less cluttered, and save users time and effort.

Most faceted navigations have top-level links. A top-level link is the main title that describes all the other links under it. It’s what users should read first before they consider the other links. Faceted minimization hides the secondary links and shows only the top-level link first. Users only have to scan the main titles to find what they’re looking for. Once they find it, they click the main title and the other links show. With this approach, the user doesn’t have to look at every single link in the sidebar. And they don’t have to go digging below the fold. They can find what they’re looking for faster and easier by scanning the main titles first.
You might have one section of links in your sidebar that is often used by your users. In this case, you can keep that section displayed and unhidden as the default. If most users will use that section, you don’t want them to have to always click the top-level link to get to the other links under it.
Faceted sidebar navigations allow you to list many links along the side of your page. But you can still overdo this and overwhelm users if you list too many. When your sidebar navigation starts to get out of control, apply faceted minimization to make your navigation simpler and easier to use. Processing information and making decisions take time and energy. And users only have so much of it.

Why External Links Should Open in New Tabs

Why External Links Should Open in New Tabs
When most designers design websites, they don’t pay much attention to links. As long as the link works and takes users to the right page, everything is fine. However, a great user experience goes further than that. There are certain links that should open in new browser tabs, and ones that should open in the same browser tab. It’s important for designers to know the difference.

Browser Tabs Have Changed Everything

Back then, many people frowned upon opening links in new windows. New windows were hard for users to manage. But the introduction of browser tabs have changed this. Instead of opening up new windows, you can now open links in new tabs. The big difference here is that browser tabs are easier for users to manage than browser windows.
When a new window opens, it covers the user’s earlier window. The user is left confused and wondering how to get back. But when a new tab opens, the user can still see their earlier tab at the top. Switching back to it is swift and easy. In fact, many users have multiple tabs opened at once when they’re browsing. The tabs metaphor is easy for users to understand. The way it’s done on browsers today makes flipping from tab to tab easy and seamless. Now that the browser has changed, the way designers target their links should change too.

Internal vs. External Links

Links that take users to another page on the same website are internal links. Internal links should never open in new browser tabs, but rather the same tab the user is on. Opening new tabs of the same website is redundant and confusing for users. If it’s the same website but a different page, the site’s navigation menu is still visible to users. They can simply use the menu to navigate back or elsewhere if they need. Keeping users in the same tab also helps them better understand the navigation flow of your site. Therefore, it doesn’t make sense to open new tabs if the links take users to the same website.
External links, however, should open in new tabs. These links take users to a different website. Many designers make the mistake of opening external links in the same tab. There are many problems with this that designers need to know about.

Back-Button Fatigue

When you open external links in the same tab, you create back-button fatigue for users. Every time the user goes to an external website they have to hit the back button to go back to your website. If they decide to click the links on the other website, they have to hit the back button even more times to get back to your site. This is a lot of unnecessary work for users.
Opening an external link in a new tab allows users to explore the other site as much as they want without having to hit the back button again and again to go back to your site. All they need to do is click the tab your site is on. There’s no excessive back-button pressing or long wait times.

Slowing Down User Flow

External links that open in the same tab can also slow down user flow. Many users who browse search engines or link sharing sites are looking for information. They’ll often click multiple links on a page to get information from different sources. Opening the external links in new tabs allows users to scan the page once, click on all the relevant links and start consuming and sifting information. The user doesn’t have to keep going back to the source page to continue scanning for more links to click. There’s less interruption in their flow.
When users do want to go back to the source page, it’s easy to do because the tab will stay open until the user manually closes it. The user doesn’t have to click the back button multiple times and wait for the source page to reload. They can easily get to it just by clicking the tab.

Overworking the Website

Opening external links in the same tab doesn’t just overwork the user, it also overworks your website. Every time the user goes back to your website it uses your site resources to load the page. You can save a lot of resources by opening external links in new tabs. If the user wants to go back to your website, they won’t need to load the page again. They can just click your site tab. This is fast and easy and doesn’t use any bandwidth. They don’t need to hit the back key or open a context menu to go back.

Inaccurate Analytics

Many times users will click an external link in the paragraph of an article to better understand the article’s context. This doesn’t mean they want to leave your site without having finished reading the article. However, your site analytics will show a different story. If your external links open in the same tab, it’ll show that users are exiting your site quicker than they actually are. This is because the external link takes users completely off your site when the link opens in the same tab. However, an external link that opens in a new tab will still keep your site tab opened as the user visits the external site. Their time on your site ends when they manually exit out of your site tab, not when they visit an external link.
A user clicking an external link does not mean that they want to leave your site. You should not treat external link clicks as site exits. The only clear exit from your site is when the user hits the close button on the tab.

External Links Affect Your Site and Users

Links that take users to different websites should open in new tabs. Links that take users to a different page on the same website should open in the same tab. If you’re opening external links in the same tab as your site, this affects both you and your users. You not only experience inaccurate analytics and make your website work harder, but you also make your users work harder and slower. In a world today where links dominate the web, making your links open the right way is almost as important linking to the right page