Maintainable Code: Using White Space For Readability In HTML And CSS


  

Right up front, I’ll offer some simple advice: In production, your code should be as performance-friendly as possible. This means, Gzip’ing, concatenating and minifying as many assets as possible, thus serving the smallest possible files and the least number of files. I don’t think anyone would argue that these suggestions aren’t best practices (even if we don’t implement them in every project).

labyrinth-comic
Well-written, readable code doesn’t create mind games and labyrinths when other developers read it. (Image: Toca Boca)

Now that we’ve got that out of the way, how can we use white space in development code to ensure that our files are as readable and maintainable as possible? Well, we could consider a number of options, starting with some basics.

Basic HTML Indentation

I think most if not all of us add basic indentation in our HTML:

Section title

Tagline

Content goes here.

The principle here is that whenever something is nested, you indent, so that it’s clear where everything is in the markup’s hierarchy. With simple HTML nesting, the content in the section is often neglected, but keeping the nesting consistent here, too, is good practice.

For example, the following sample code is fairly readable, even with no nesting:







 

However, with much more content in the section, nesting could make it easier to scan the contents:



  
    
    
    
    
    

    
    
    
    

    
    
    
    if (location.host == 'h5bp.github.com') location.href = '//html5please.us/'

  
  
     
  

This last chunk of code is taken from the HTML5 Please website. As you can see, when the content in the section starts to get larger, indenting makes things a bit easier to digest at a glance. Notice that the and elements are indented, because they are both immediate children of the element.

Of course, some developers might have a slightly different method of indenting in certain areas, but the idea is basically the same; the intention is to make the code easier to read in a development environment.

Basic CSS Indentation

In addition to indenting HTML, many developers (me included) will do matching indentation in any corresponding CSS. The following code would match the HTML shown in the first example above:

header {
    color: blue;
}

    hgroup {
        color: green;
    }

        hgroup h1 {
            line-height: 1.5;
        }

        hgroup h2 {
            font-size: 15px;
        }

    nav {
        background: purple;
    }

        nav ul {
            float: left;
        }

            nav ul li {
                font-size: 20px;
            }

                nav ul li a, nav ul li a:visited {
                    text-decoration: none;
                }

.main {
    border: solid 1px #ccc;
}

To some, this seems a bit obsessive. But I prefer it because it helps me to scan the CSS and find matching hierarchies without having to read each selector. Of course, this type of hierarchy in your CSS should be used sparingly if you’re implementing modular CSS principles that encourage class-based modules and limited use of the descendant selector (for example, ul li).

Certainly, some of the code above is kind of awful; I wouldn’t recommend tying your heading and list styles to a specific context like that. But for the purpose of understanding this concept of indenting CSS, look at it as a theoretical example.

The point is that you have the option to indent CSS to match the HTML’s structure, thus making it easier to scan and easier to make sense of relative to the markup.

Of course, as is the case with a few things mentioned in this post, some of this doesn’t apply when you’re using a CSS preprocessor. For example, the nested selectors option for Sass would make this last tip quite different in such an environment.

Readable CSS3

Let’s take our abuse of white space even further. Many new CSS3 features allow for either comma-separated or space-separated value sets. Two simple examples are multiple backgrounds and transforms. Let’s see how we can make these easier to read:

.example {
    background: url(images/example.png) center center no-repeat,
                url(images/example-2.png) top left repeat;
                url(images/example-3.png) top right no-repeat
}

.example-2 {
    transform: scale(.8)
               skew(20deg, 30deg)
               translateZ(0);
}

Notice what we’ve done here? Instead of keeping the entire value on a single line (which can get lengthy in some cases — especially when gradients and vendor prefixes are involved), we’ve put each value set on a new line, aligned with the one above it.

Thus, each of the three backgrounds is on its own line, and each transform function is on its own line, left-aligned with the first of each example.

Generally, this might go against the idea of having a single property per line (assuming, of course, that you’re not doing single-line rule sets). But when compared to the alternative of potentially really long lines, this is a good option, and it makes these rule sets very easy to read.

Dealing With Vendor Prefixes

As mentioned, if you’re preprocessing your CSS or using -prefix-free, then this advice doesn’t apply. But you could manipulate white space to make your vendor prefixes easier to read at a glance:

.example {
    -webkit-transform: scale(.8);
       -moz-transform: scale(.8);
         -o-transform: scale(.8);
            transform: scale(.8);
}

Here we’ve lined up the colons so that the values align, making it easy to scan all values to ensure they’re the same. I can’t tell you how many times I’ve adjusted only the WebKit value in a rule set like this and forgotten to do the rest. Of course, this illustrates the importance of preprocessing, but if you’re not doing that yet, then this use of white space is a good option to consider.

Additionally, many text editors offer a feature called “block edit” or multiline editing. This is available in Sublime Text, Vim, Coda and probably most others. Using this feature is that much easier when the values you’re changing are aligned vertically.

Readable File References

The gist of this next suggestion comes from a tweet by Twitter Bootstrap cofounder Jacob Thornton. The idea here is that if a list of file references is contained in your document, you can make them easier to read by doing something like the following:



  
                
                               

The example above is taken directly from Bootstrap. Here, all href attributes of the elements are aligned. This makes it easier to refer to or adjust a tag because the update will usually be to the value of the href attribute.

Of course, this somewhat violates the rules of indenting HTML. So, alternatively, you could opt for this:





This latter example seems cleaner and has the bonus of aligning the other attributes, although that’s not as necessary in my opinion.

But wait. What if you don’t care that the href attribute is listed last (which seems to be the custom and is unnecessary for validation)? Then you could do this instead:





No white space tricks needed here, because the href attributes align just fine. But if you’re bothered by the lack of alignment of the other attributes, or if you just can’t stand the thought of the href attribute being listed first, then you’ll have to opt for one of the preceding solutions.

Readable Conditional Classes

The concept behind the alignment of attributes is nothing new. HTML5 Boilerplate has been doing this sort of thing for some time now with its IE conditional classes. Here’s what that chunk of code looks like in the latest version:




  <!--

In this case, the class attribute on the opening tag in each conditional (and, incidentally, the tag itself) is being aligned, because this is the part of the code that’s most relevant to readability and maintenance, and the part of the code that would suffer most in readability if this alignment were not present.

Readable Comma-Separated Selectors

Sticking with Boilerplate, let’s go back to CSS. Here’s something used in that project’s main style sheet:

html,
button,
input,
select,
textarea {
    color: #222;
}

Here, instead of keeping all of the comma-separated selectors on a single line — which would be more difficult to scan — each selector is put on a new line. This can be helpful when the selectors are somewhat lengthy, as in this next example, also taken from Boilerplate:

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

Similar to the idea behind aligning HTML attributes discussed above, this vertical alignment makes the code a breeze to scan through when compared to scanning a single seemingly never-ending line of comma-separated selectors.

Can Your Text Editor Help With Any Of This?

As a long-time developer who has grown accustomed to coding by hand, my knowledge of the features of different text editors is fairly limited.

Some text editors or IDEs might do some of this automatically. Also, plugin developers can use some of these patterns to create plugins or extensions that do this sort of thing automatically or at the click of a button.

If you have any suggestions of built-in tools or extensions to text editors that can assist with this, I’m sure Smashing Magazine’s readers would be glad to hear about them.

Conclusion

We’re all encouraged to do whatever we can to make code in a development environment as easy to read and maintain as possible. I hope these suggestions will improve your code in this way.

And knowing that this use of white space won’t bloat our files is comforting — after all, this is not for production code. So, do whatever you feel is necessary to make your HTML and CSS easier to deal with, and be sure to minify those assets when deploying to production.

Finally, if you have any suggestions on using white space in HTML or CSS, we’d be glad to hear them.

(al)


© Louis Lazaris for Smashing Magazine, 2013.

Smashing Magazine

Function Over Form: Designing For The Reading Experience


  

With the rise of Web fonts as well as affordable hosted Web font services and ready-made kits, typography is reclaiming its title as design queen, ruler of all graphic and Web design.

At the same time, for far too many designers, the main concern about typography today seems to be aesthetic in nature. The problem is, we tend to use typography and lettering as two interchangeable terms, which they are not. A quick look at the “typography” tag on Dribbble reveals this trend.

The allure of well-executed lettering — and, boy, I could spend hours just looking at lettering portfolios! — can affect the way we view typefaces, because both typography and lettering share common visual concepts. If we seek only the next most Beautiful Typeface™ all the time, this habit alone can drive us away from the functional role of typefaces and their advantages as versatile, reusable and flexible design systems.

Moreover, we are often eager to try the latest OpenType feature, prettify our copy with discretionary ligatures, slap on partially executed CSS hyphenation, and then stare at our masterpiece in awe, unaware that anyone other than a typography geek couldn’t care less. Of course, reality hits right at the moment that the text has to be read and understood by normal people on a variety of devices, from the latest Retina laptops to 72-DPI cathode-ray-tube monitors with Windows XP to a range of sci-fi smartphones that can measure your blood pressure.

“Good typography does not look nice to please type nerds. Primarily, well set type reads well.”

– Oliver Reichenstein

Most articles on the Web are optimized for instant ingestion — does “reverse pyramid” sound familiar? Fast exchange of information is in the Internet’s nature and fits a reader’s short attention span. People visit websites and applications because they primarily seek information; rarely do they seek typographic pleasure. Don’t get me wrong: I love typographically creative headlines and decks that grab my attention — but at the same time, we can’t neglect the need for overall balance and legibility in body copy.

Let’s start!

First Thing’s First: Project Research

Seamlessly digesting written matter is possible only when the typography is well thought out and legibility is facilitated by a considered reading experience. As in other fields of design, before doing anything else we should conduct some research. In developing the habit of research, we will not only discover valuable data, but also develop our ability to quickly jump into the reader’s shoes, shifting focus from our worst enemy — our own ego (which I play tug-of-war with all the time).

As you are most likely aware, the main components of a digital experience are content, context and the user. You probably address all three in almost every design project. But if we focus exclusively on typography within each of these components, then we’d find a handful of assessment methods and some considerations that would be useful to take into account and that would ultimately improve the overall reading experience.

Content

The best way to start a typographic design project is by reading the content. Seriously, every designer is intelligent enough to evaluate who this content is for and what it should be communicating. But apart from rating the quality of the content and listing its structural elements, we can also gauge comprehensibility, reading time, purpose and, finally, lifespan.

Cover All Typographic Elements

Upon reading the content, think about the structures or elements you have encountered and list them. Use the list as a starting point for a simple style guide. Apart from the normal paragraphs, headings and editorial accessories, you’ll find other — often overseen — elements, such as areas of emphasis, quotations, emphases within quotations and, very important these days, data tables and figure captions. Your perfect font should have enough family members to cover all of these elements.

In plain hypertextese, make sure to cover all HTML elements. At this point, you could even create sample HTML and CSS files containing all of the required elements and rules and save it as Project-Typography.html. As you can probably guess, this file will be the foundation of the project’s typographic system and will come in handy when you start designing responsive breakpoints.

Gauge Reading Time

Reading rates range anywhere from under 100 words per minute to a few thousand; most adults read between 200 and 250 words per minute. We can calculate the reading time for any given text quite easily by dividing the number of words by 250. If sample content for your project is available, simply throw it into a local installation of your favorite CMS and run it through a simple script to estimate reading time.

Depending on the situation, estimating reading time can help us determine the spacing within paragraphs and establish just the right rhythm and reading pace. If the reading time is long, we could break the text into smaller parts or simply introduce a pull quote at a strategic point, where it would double as a milestone.

Assess Readability and Reading Ease

Many readability tests provide an estimate of the school grade needed by the reader to understand the text, and knowing such parameters is useful. For example, if the matter is complex, you could probably introduce some editorial devices to keep the reader on track, or accommodate a greater number of footnotes with their own set of accessories.

Furthermore, when you are collaborating with a copywriter to tweak content and typography, these tools will make it easier to track differences between versions.

One such test is the Automated Readability Index (ARI). ARI focuses on the number of characters, words and sentences, thereby making it useful for real-time monitoring. The Flesch–Kincaid Grade Level test, on the other hand, focuses on syllables rather than characters, thus making it somewhat more processor-intensive for real-time assessments.

Another valuable test is Flesch Reading Ease. It is calculated according to words, sentences and syllables; the resulting score helps you determine the level of complexity of content. Most major languages have their own version. Although this tool is new to some of us in Web design, textbook publishers and government agencies have been using it for years to gauge the complexity of learning materials for different grade levels.

Calculating the reading ease score manually for each piece of content would be an obvious sign of masochism, so I suggest checking out the handy Article Readability Stats, a PHP script that we at Creative Nights developed for our own projects.

Content Strategy, Information Architecture and Microcopy

If we step out of typography for a moment into the field of content strategy (the discipline of planning and governing content and of defining editorial processes) and information architecture (the discipline of organizing and describing content), we can anticipate some potential issues.

Thinking about the content’s lifecycle protects us from the urge to typeset according to the latest trend. The next time an article is republished, we can prevent the editor’s rage from seeing leftover styles that weren’t removed in preparation for a redesign.

Category labels — typically defined by an information architect — can make the Web designer’s life miserable, because the space in a navigation bar or column is limited. I’d bet that at some point in their career, every Web designer has tried to rename or shorten category names in order to fit the available space. Of course, we could always reduce the font size or choose a condensed type, but if all else fails, we talk to the information architect to find a solution on their end.

Apart from articles, we must also typeset form labels, instructional copy, small print, interactive elements (such as buttons and links) and other text that clarifies tasks. All of this tiny copy is referred to as microcopy, and it is a fundamental ingredient in effective interaction design.

Context

With recent developments in Web standards, designers are now building websites that are getting closer and closer to the ideal of “One Web,” accessible to everyone and everywhere. Even though achieving such universality with all types of projects is difficult, we know that mobile doesn’t just mean browsing the Web on a smartphone while on the go.

We also know that tablets are used to give presentations, to check Twitter during breakfast or to read articles while sitting on the toilet (anyone who neglects this fact doesn’t understand the needs of users). The screen real estate of the coming generation of laptops puts a 96-DPI 30-inch desktop monitor to shame. We admire the Web’s universality, but at the same time we should be aware of the diversity of users and devices.

Software Concerns

Users on Windows systems with the ClearType rendering engine benefit from well-hinted fonts. The trouble is that hinting is a time-consuming process, and not all typefaces for the Web are fully polished yet. Therefore, additional testing in Windows browsers should form part of your regular routine.

 screenshots of Verdana, Proxima Nova, Arial, and more.
These screenshots of Verdana, Proxima Nova, Arial, Adelle Sans and Georgia at 16 pixels (except for Proxima, set at 18 pixels) were taken on Firefox 18 on Windows 7. Proxima and Adelle are rendered as Web fonts, and the others are the usual suspects that come preinstalled on most OS’. The top five lines were taken with ClearType turned off.

Also, keep in mind that each Web font service might deliver slightly different fonts. A font might yield good results when delivered through one service but look barely adequate when delivered through another. I’ll speculate that the reason for such differences, if any, is primarily a lack of time invested — that is, a lack of the time needed to properly hint a font, as well as a scarcity of font-hinting experts.

Luckily for us, Web font service vendors are continually improving the quality of fonts, and eventually everyone’s fonts will be spruced up. Because a lot of work goes into maintaining proper fonts, I encourage you to buy fonts and to subscribe to paid Web hosting plans, which (among other things) will speed up the hinting efforts of font foundries. The greater the demand, the faster the process.

If supporting Windows users is mission critical for your project, then consider manually hinted typefaces, such as TheSans Office from LucasFonts (these guys are known for their obsession with hinting) or the numerous other typefaces designed for Microsoft Office applications (their names will usually contain “Com,” “Offc” or “Office”). If selecting a specialized typeface for an audience with older Windows systems is not worth the trouble, then just stick with the tried and tested Arial, Georgia or Verdana.

For more in-depth information about font rendering, read “A Closer Look at Font Rendering” by Tim Ahrens.

Hardware Concerns

A problem we are facing across the industry is the diversity of pixel densities; as a result, typography is not spared either. One interesting solution is to embed graded fonts for different densities, just as print designers use graded fonts to more precisely control the effects of ink on paper. Read more about this approach in Oliver Reichenstein’s article “New Site With Responsive Typography.”

Adelle set at 16 pixels.
Glyphs are rendered differently even on devices from the same manufacturer. Shown here is Adelle set at 16 pixels as rendered on an iPhone 3G, iPad 3 and iPhone 4S, enlarged in Photoshop, from a Web page screenshot.

Another example is typesetting for screen billboards and TV screens, which often require thicker weights and more weight contrast. In such cases, you would skip two weights on a scale and combine the regular style with the extra bold. Previewing such designs on your desktop or Retina laptop is not enough. As with designing for mobile, we have to test on real hardware.

The Interface Type

Hardware and software aspects aside, context also refers to the type of interface. For instance, on content-driven news portals, magazines, novels and textbooks in a digital setting, strings of sentences should have a clear structure, directly connected to each other and that form a linear reading path.

Topics on content-driven websites are usually diverse (even on niche websites), and a story needs to be introduced clearly in order for the reader to understand it. (Remember the editorial devices from above?)

On the other hand, information in Web applications is straightforward, usually bare-bones and factual, with easily comparable items or data, most often constrained to a certain timeframe. Unlike sentences in linear text, bits can be read and comprehended in isolation and are, therefore, open to the reader’s interpretation. We can safely assume that the user will jump randomly, in a non-linear fashion, from one bit of information to another.

With Web applications, the context of content is mostly predictable. Some typical use cases are checking sales figures; analyzing website statistics in tables, diagrams and charts; editing date- and time-related notes; and, in the case of Web mail, checking whether you are the lucky winner in the Nigerian Royal Lottery.

The User

On the Internet, everyone is our target customer, especially if we are building a multilingual system. If a button has just enough room for “Return” in English, then “Retour” in French, “Zurück” in German, “Povratak” in Croatian and “Visszatérés” in Hungarian might not fit.

Accessibility Concerns

Dyslexia is an impairment to a person’s ability to read. For instance, a dyslexic brain sees characters as images and rotates and mirrors letters. As a result, a lowercase two-story “a” with a weak tail might appear the same to a dyslexic person as an italic “e.”

In addition, most characters in geometric typefaces are hard for people with dyslexia to read because of similarities in form and shape. The mirrored “p” might look the same as a “q,” and a rotated “n” might look the same as a “u.” This doesn’t mean we should immediately switch to specialized typefaces, but being aware of such conditions is a part of the Web designer’s literacy.

To complicate matters, dyslexia occurs with another learning disability, attention deficit disorder, in about every fourth case.

Futura and Open Dyslexic.
Added gravity keeps the letters in place. Shown here are Futura and Open Dyslexic.

Font smoothing on the screen is possible thanks to red, green and blue subpixels. Unfortunately, for a small percentage of the male population, some typefaces appear sharper or blurrier, lighter or fatter than for the rest of us, simply because the red subpixel isn’t distinctive enough. With free tools such as Color Oracle, seeing how your typeface of choice performs for the color-vision impaired is easy.

Perceivement of anti-aliased letters.
Those with color-vision impairments perceive anti-aliased letters differently.

Selecting A Typeface For Function Over Form

Contrary to popular belief, having an eye for the perfect typeface is not an innate gift. Sure, talent will give you an initial advantage, but that will take you only so far. Train yourself to learn about the project at hand, and insight into suitable typefaces will come, thus helping you narrow the pool to a few appropriate candidates.

A little digression. Many tutorials and how-to’s have been written about choosing the appropriate typeface based on atmosphere and on look and feel. Designing atmosphere, evoking emotions and visually distinguishing a brand from its competitors is the responsibility of the graphic and UI designers. A typographic designer, or typesetter, takes a different angle, starting with the utilitarian needs and goals of the project, and developing from there. Both aspects are often required for a successful, well-rounded project.

Because these goals are so different, we have to be leery of suggesting font combinations and using less-than-specific adjectives such as “beautiful” and even the less-dramatic “nice” without providing context. A typeface can only be judged in the context of a particular situation. If a typeface is observed in isolation, then we must evaluate it at a strictly technical level.

When I see Comic Sans used on an invitation to a kindergarden party, the first thing I’ll do (of course) is roll my eyes. But at some point, I have to be honest and admit that it’s appropriate to the audience — my kids and their friends — as long as I don’t encourage them to use it everywhere. But if I saw Comic Sans on a company memo, I’d probably go postal.

Serif vs. Sans: Who Started It?

Many beginners have a hard time choosing between serif and sans-serif typefaces. As always, it depends on the situation, but it should never be a matter of the typographer or client’s personal taste. There is no difference in legibility between the two, especially in this era of high-density screens.

Sometimes a project allows us to cut corners, and if we do our homework and learn about the content, we can make informed decisions. For example, if we are presenting vertically oriented data (for example, a table of exchange rates or a list of product prices), then it would probably be better to use a typeface without serifs, which usually adds a horizontal emphasis. On the other hand, because serifs encourage horizontal flow along the line of text, they are more suitable for a set of linear thoughts or where vertical space is scarce.

We all know it, but we often forget to step back and see the bigger picture in a project. For instance, I like the reasoning of Vitaly Friedman and Elliot Jay Stocks in their decision to go with a sans serif for Smashing Magazine’s body text. Upon taking a bird’s-eye view and observing the page’s layout and interface as a whole, they concluded:

“Because there’s a lot going on visually on Smashing Magazine — screenshots, buttons and noisy ads — a sans-serif felt like a more sensible, uncluttered route for body copy.”

– Vitaly Friedman and Elliot Jay Stocks

Letter Legibility

Another important test of legibility is how different each glyph is from the other glyphs in a single typeface. Designers use pangrams, or short test strings, to evaluate and compare typefaces; for examples, the famous “The quick brown fox jumps over the lazy dog,” “Handgloves” and “Hamburgefonstiv.”

The text “aegh! iIl1 0O,” devised by designer Jon Tan, goes a little further. It is a good way both to get a sense of a typeface and to check the distinctness of the “i,” “I,” “l” and “1” and of the “0” and “O.”

We can extend such strings even further and include italics, small caps and numerals. For example, we could extend the string with an italic “e,” just to make sure it’s not too similar to a rotated lowercase “a,” especially at smaller sizes where character detail can get lost.

League Gothic, Gill Sans, Myriad Pro, Neue Helvetica.
Try to avoid ambiguous letterforms. Top to bottom: League Gothic, Gill Sans, Myriad Pro, Neue Helvetica.

Foreign Affairs

Support for international visitors is a must. If you are about to set the whole website in a language that you are not familiar with (say, Arabic or Vietnamese), then you’ll probably need a one-on-one lesson with a local typographer. But most Web designers will build user profiles for their international audience, and we have to make sure that all characters are supported and that the typeface works in languages less common than English and Spanish. Each language has a particular critical combination or two.

It’s not uncommon to see a character sequence of “gy” in Hungarian or “ij” in Ijekavian dialects in some South Slavic languages, not to mention digraphs (“ch,” “dž,” “ij,” “lj” and “ty”) and trigraphs (“dzs” and “sch”), which are usually represented with two and three separate glyphs, respectively.

As a curiosity, in the Italian alphabet, the letters “k,” “j,” “w,” “x” and “y” are used only for words adopted from other languages, and some of them are used strictly colloquially — for instance, “k” as an emphasized “c” — or so I heard when I cut a guy off in traffic the last time I was in Italy. But I digress. The slightly reduced alphabet results in frequent letter combinations such as “cc,” “ll,” “tt” and “zz” next to — or surrounded by — “o” or “i.” You can already guess that these combinations can make for some awkward spacing.

In southeast Europe, family names often end with “č” or “ć,” and no one likes when a letter in their first or last name is stripped of a diacritic or, even worse, rendered in a fallback typeface. Danish and Norwegian, for example, use “ø,” and German uses “ß” — and those are still only within the Latin alphabet.

Know the characters and combinations in your target language.
Know the characters and combinations in your target language.

In order to cover the extended Latin alphabet, we obviously have to choose a typeface that covers all Central European characters (i.e. use paid fonts). But in cases of the aforementioned letter combinations in less common languages, it wouldn’t hurt to consider typeface candidates that support those particular languages, because at the time of writing, kerning is still not possible with CSS (no pun intended).

We Read Familiar Typefaces Best, But We Learn Better With Unfamiliar Ones.

People are believed to read best in familiar typefaces (PDF, 11.5 MB). Even experts — namely, Zuzana Licko and Erik Spiekermann — say that we read best in what we read most. Learn about the history of the typeface you’re considering and compare it to the usual suspects for the target audience.

Skolar, a typeface by David Brezina, was designed for scholarly and multilingual publications, where people are used to seeing Times New Roman. Skolar is fresh and modern, yet similar enough in features and appearance to Times New Roman to be easily adopted by this user group. It’s a safe bet and a good option to begin with, but by all means do experiment and try alternatives that might appeal to your target audience.

Differences between Times and Times New Roman.
Skolar as a replacement for Times and Times New Roman? Can you spot the difference between the two Times’?

A recent study by Connor Diemand-Yauman, Daniel M. Oppenheimer and Erikka B. Vaughan on the “Effects of Disfluency on Educational Outcomes” (PDF, 1.3 MB) found that information rendered in hard-to-read fonts was more easily remembered than information rendered in fonts deemed easier to read. The study showed that deeper processing stimulated by disfluency led to improved memory performance. This doesn’t mean we should automatically select the strangest typeface on the planet, but considering an alternative to a popular typeface does make sense.

Display Typefaces in the Responsive Era

Condensed gothics and grotesques as well as specialized decorative typefaces are being rediscovered on the Web. They add style and weight, functioning especially well as attention-grabbers in mastheads and as anchors in lengthy text. Stylistic suggestions are beyond the scope of this article, because headlines on the Web are often written to conform to SEO best practices in order to attract more visitors, which is a somewhat different function from headlines in print material. However, let’s look at a potential pitfall in setting headlines in a condensed typeface on the Web, where the context is never static.

If changes in screen orientation and aspect ratio are neglected, then a multi-word headline set in a “skyline” typeface (i.e. a tall condensed sans serif) might work with landscape-oriented and desktop-sized breakpoints; at the same time, it might occupy too much vertical space on a smartphone in portrait orientation, especially if the original single-line headline is pushed onto a second line. Merely reducing the font size to fit the element could help, but the result might not be as legible as the text on a desktop screen.

The opposite also applies. If we are designing mobile first, then a big bold headline that works perfectly on a tiny screen might be too loud if literally transposed to desktop sizes.

An extended companion to a condensed typeface set at a smaller font size could provide a better match where vertical space comes at a premium. When the extended typeface is too tiny, the condensed partner could step in.

headline set in the League Gothic on a single line.
This headline, set in the League Gothic on a single line, is barely legible on mobile. Set on multiple lines, the headline occupies too much vertical space.

Nimbus Sans Condensed and Nimbus Sans Extended in action.
Nimbus Sans Condensed and Nimbus Sans Extended in action.

Combining Typefaces

Typefaces are combined to create tension and to generate interest in a design. In most cases, however, once the reader is pulled in, favoring order and structure of composition over the beauty of letterforms will improve the flow of reading, especially on low-resolution screens, where subtleties and details of typographic accessories are not immediately evident. Consider this piece of advice as a last attempt to talk you out of combining very different fonts, unless absolutely necessary.

As a rule of thumb and in order to avoid a complete typographic disaster, combine typefaces with matching x-heights. Comparing x-heights at the same font size is a litmus test to see whether words set in different types can coexist. Always keep in mind that typesetting for the Web should be bulletproof and future-proof. That being said, maintaining typographic harmony is not the easiest task if elements sitting on the same baseline need different letter sizes as compensation for mismatching x-heights.

Aller combined with Minion Pro, Georgia and Adelle.
Aller combined with Minion Pro, Georgia and Adelle. Notice how Minion Pro and Georgia call for additional adjustments to line height.

A Safe Bet Approach

The easiest solution to combining typefaces is to follow type relationships and your own common sense.

A typeface that is a member of a bigger system can be combined with other family members along any of the axes (such as weight, width and cut), so being able to use typefaces from the same type family will come as a relief. Look for extended families or super-families that have more than a few basic styles (including regular, italic, bold and bold italic). Extended families include everything from thin to black weights and sometimes multiple widths, while super-families, also referred to as type systems, additionally contain sans-serif and serif companions, text and display cuts and sometimes graded fonts.

Don’t worry too much about exact classifications, because categories are not always consistent from foundry to foundry. Plus, the boundary between extended families and super-families is not always clear. For example, some collections include sans-serif and serif in multiple weights but not multiple widths. Remember, though, that most type families have only a limited number of basic styles, while only a few dozen are versatile enough to cover all typographic needs. (A few dozen out of the hundreds of thousands of typefaces in existence today is a tiny fraction.) If you have trouble combining typefaces, versatile collections are always a good option to begin with.

JAF Bernino Sans has multiple weights and widths.
JAF Bernino Sans has multiple weights and widths. The grayed-out letters are fake italics, also referred to as slanted romans. Some browsers are capable of distorting fonts into a slanted shape on the fly with CSS, but pseudo-italics are considered a typographical crime.

Typefaces designed by the same designer are often a smart combination, because proportions, shapes, strokes and angles will share the same DNA. Note the typefaces designed by Jos Buivenga, Veronika Burian, Matthew Carter, Nikola Đurek, Adrian Frutiger, Jose Scaglione, Mark Simonson and Erik Spiekermann, to name just a few of my heroes, and try to spot each designer’s signature.

As a last resort, combine typefaces from the same foundry, because a foundry will normally offer typefaces that can be combined. A smart designer subscribes to typography-related newsletters and, consequently, gets exposed to a significant number of proven and reusable combinations, as suggested by the experienced designers and typographers who work at foundries. As a bonus, your newsletter folder will become a nice reference archive over time.

If you still want to experiment on your own, create enough contrast between typefaces to achieve a comfortable balance. Avoid typefaces with competing characters, which would create too much noise and distract the reader. If two typefaces are too similar, though, the reader might get irritated just because they can’t clearly see the differences. Combining two neighboring weights (such as regular and semibold or bold and extra bold) shouldn’t become a habit unless you absolutely know what you’re doing.

As with cooking, start by preparing simple edible meals. Then, after you’ve gotten some experience in not poisoning people, you can safely put the cookbook on the shelf and start experimenting with exotic spices and your own routines. If you are dying for some practical examples, here are a few handy articles:

Editorial Accessories

Display and decorative typefaces are appropriate for short text snippets, such as headlines and pull quotes, because they set the tone and atmosphere and break up long copy (remember the reading-time assessment from above?). Text typefaces are utilitarian and suitable for long reading. Reading can get boring after a while, particularly on an attention-hostile technology such as an Internet-connected computer.

“Designers like even grayness, which is the worst thing for a reader.”

– Erik Spiekermann

Insert an occasional break with a heading or pull quote, to nudge the reader along. Pull quotes that highlight important facts from the text would benefit from a display typeface. Because headings are a part of the main text, they are best set with a variation of the primary typeface (small caps, for instance). As stated, this is more of a safe bet than a rule set in stone.

We Have A Responsibility

Two important factors should influence your decisions. First, if they don’t like your typographic choice, a reader can change it via the customization options built into the application or device. And if they do that, they will usually change it to something more generic, thus ruining your typesetting altogether. Back in the day, when we combined absolute units for line heights with relative units for letters in Internet Explorer (or so I’ve heard), even a slight increase in letter size would bring chaos to the page.

Secondly, the absence of a fold or any physical boundaries of the page is both a curse and a blessing. On the positive side, the space for content on the screen is virtually infinite. On the negative side, designing a balanced layout becomes more difficult because, in most cases, it won’t be seen all at once from top to bottom. This is why editorial accessories are valuable features that can help us design a better reading experience. Once the user scrolls further down the page, we can’t expect them to run a marathon all the way to the end.

When designing for everyone, we shouldn’t assume anything. We ought to accept that our typographic designs will be seen on various hardware devices, in a range of pixel densities. We have to make sure our text is as legible as possible when seen in the virtually limitless combination of variables such as space, time, cognition, social conditions and physical conditions. The days of hard and fast rules are gone, and our responsibility is to learn everything we possibly can about a project in order to make informed decisions and establish a solid design concept.

(al)


© Marko Dugonjic for Smashing Magazine, 2013.

Smashing Magazine

Converting The Prototype: iOS Prototyping With Adobe Fireworks And TAP (Part 3)


  

In the previous parts of this tutorial (part 1 and part 2), we looked in detail at the building blocks of our design in Fireworks (pages, shared layers, symbols, styles), and we started to make a demo prototype in Fireworks.

The demo prototype had six pages, linked together by hotspots, and each hotspot was customized for use with TAP. (Which page will the hotspot link to? Which gesture will initiate the hotspot link? Which transition will animate once the appropriate gesture is used?)

Now that the six-page Fireworks PNG file is ready, it’s time to prepare it to be exported as a click-through prototype and then converted (with the help of the TAP extension) to an animated, gesture-based prototype that we can use on an iOS device.

Export The Fireworks Project

Create the Project Folder

First, we create the project’s folder. This folder will contain and organize our Fireworks project, as well as the TAP assets needed to create the prototype:

  1. Create the project’s folder, and name it CookbookApp.
  2. In the folder, create another folder named Library.

When you export the project from Fireworks, you will export into the Library folder. TAP will always look for project files in the Library folder, and it will create and place your prototype files in the project’s folder. If you forget to create a Library folder, Fireworks will remind you when you export the project.

Export as LBI

After you have created the project folder and have finished customizing all of your pages and hotspots, the next step is to export your Fireworks PNG in a format that TAP can understand. Ultimately, your work will be an HTML prototype (i.e. a set of HTML files) that can be viewed full screen on an iOS device; but because you will be using TAP to create the prototype, you cannot directly export to HTML in Fireworks.

Instead, export the project as a Dreamweaver Library (.lbi file format). While this format cannot be read directly by a browser, TAP will convert the LBI into HTML through the use of custom-developed PHP and JavaScript (jQTouch and jQuery) code later on.

Here are the steps:

  1. Start with the menu File → Export.
  2. In the “Export” dialog box, use the following settings:
    1. In the “Save as” field, type cookbook (the file extension is automatically added).
    2. Navigate to the directory you wish to save your project to.
    3. The “Export” drop-down menu should be set to the Dreamweaver Library (LBI).
      Note: If a warning dialog box appears, click “OK” and continue with the export:
      Warning dialog box in Fireworks, when saving in LBI file format
      Warning dialog box in Fireworks when saving for the first time in the LBI file format.
    4. Create a new folder and name it “Library,” and then click “Choose.”
    5. In the “Pages” drop-down menu, select “All Pages.”
    6. Enable the “Put Images in Subfolder” option.
    7. Finally, when ready, click the “Export” button.

The “Export” dialog box should look similar to the one below:

Export dialog
Export your prototype as a Dreamweaver Library item (LBI) using the settings shown in the screenshot. The LBI file must be saved in a folder named “Library” in order for it to work properly.

Download TAP

At this point, you have completed most of the hard work required to make the prototype come to life. You are almost ready to export your work, but before doing so, download the TAP utility. This is a ZIP file with some folders containing PHP, jQuery and jQTouch scripts. Unzip the file; note that one of these folders is named “Library,” into which you will eventually copy (or directly export) your prototype’s LBI files.

Convert The Prototype Into A Working iOS Prototype

Upload

Your project is now uploaded to a Web server. Make sure that your Web server has PHP installed, because the TAP installation process requires it. First, we need to upload the TAP folder that we downloaded earlier (which now also has our project exported to the Library subfolder!) to a server that can execute PHP.

Set File Permissions

Next, to make TAP work correctly, we need to set the correct permissions (also known as CHMOD) to access the files and folders we have uploaded. You can set the file access properties using an FTP transfer program. No matter what software you use, the process is roughly the same. I use Transmit on the Mac, but you can use FileZilla (if you are on Windows) or another FTP client of your choice.

In Transmit, CHMOD is accessed via the “Get info” command:

File Permissions (CHMOD)
Set up the file permissions so that everyone can read, write and execute them (known as “777” in the octal numeral system) to ensure that the prototype runs correctly.

Set the access to “777,” either by typing 777 in the “Octal” field or by checking all of the boxes for “Read,” “Write” and “Execute.”

Note that for the purpose of this article, these file permissions are for use on the remote server on which you will be hosting the prototype, not for use on a local server (although you could, of course, run TAP on a local server, as long as you have Apache and PHP running on your Mac or Windows machine).

Convert to iOS Prototype

The next step is to open up the dashboard where all of the settings are available to convert your project into a real HTML website (i.e. HTML prototype).

First, load the “Build” panel in Safari on your iOS device by opening http://www.yourwebsite.com/path_to_prototype/foldername/build (see an example of a build panel).

This step can also be done by loading the Build panel on a desktop machine, but it is still recommended that you use the Safari browser.

TAP Build Panel
TAP’s Build panel (Larger version)

In the Build panel, you can configure the settings for the prototype. You can also upload the home-screen icon and the startup screen from here. To save your settings, click “Build prototype.” If you have made any mistakes in the previous steps of this tutorial, the page will notify you with a warning at this point.

If there are no errors, click the “Go there” link, which serves as a shortcut to the prototype.

Note: You can also manually go to the website by typing in the following address: http://www.yourwebsite.com/path_to_prototype/foldername/. This is useful for when you are using the Build panel on a desktop to set up the prototype.

You will see a black screen and maybe a brief flash of your website appear for a second, which is normal; this page is not yet your prototype. One final step is needed, although the step you take will depend on the browser you are using to view the prototype:

  • Safari
    To actually see your prototype, you must add a bookmark for this page and add the bookmark to the home screen.
  • iCab Mobile
    I have found that iCab Mobile is a better browser to showcase a prototype, because you can view it in full screen with no chrome, and also view it offline. (Details on using the browser will be shared later on.)

Note: While iCab provides a more robust and sophisticated environment to work with your prototype, as of the time of writing, the newest version of iCab can’t directly build the prototype. However, there is a workaround that allows you to use iCab. To use iCab, first open and run the Build panel in Safari. Once the “Build prototype” button has been pressed in Safari and the black screen appears with a brief flash of your prototype (as described earlier), you will be able to copy the URL into the address bar and then paste it into iCab Mobile.

Icon and Startup Image

Use the Build panel to upload the application’s icon and the startup image (you can do this only in the Safari browser on a PC or Mac, not on an iOS device). It does not matter how these files are named. Putting them in the add-ons folder is recommended.

Note that startup images do not load reliably for some reason. Sometimes they show up as the prototype is loading, and other times the startup image is skipped and the first page of the prototype is loaded instead. I am not sure why this happens, but whatever happens, your prototype will still load correctly.

Remember that the startup images have certain dimensions. For example:

  • iPhone 3
    320 × 460 pixels
  • iPhone 4 and 4s (Retina)
    640 × 920 pixels
  • iPhone 5 (Retina)
    640 × 1136 pixels
  • iPad 2
    768 × 1024 pixels
  • iPad 3 (Retina)
    1536 × 2048 pixels

(The newest version of TAP, 0.47, officially supports all Retina display resolutions.)

App Icon
An example of an app icon that can be used when your HTML prototype is launched from the iOS home screen, to make it feel more like a real app.

Updating the Prototype When Changes Occur

Here are the steps for updating the prototype if needed:

  1. Make the changes in your Fireworks PNG document.
  2. Export the file again to the Dreamweaver Library format (LBI), and replace the folder on the server. (To be on the safe side, delete the folder on the server first and then upload the new folder.)
  3. Open the Build panel in your browser, and click “Build prototype.”
  4. Add the prototype to the home screen of your iOS device.
  5. Launch the prototype from the home screen. Done!

Some Tips

  • When you are ready to export the new LBI files, delete all of the files in the “Library” folder before exporting from Fireworks. This will save you from having to OK a lot of messages later on.
  • If you’ve fixed technical bugs in the prototype in Fireworks but don’t see them updated in the browser, try clearing the browser’s cache (the browser may be loading older cached files).
  • Remember to rebuild new exports before testing changes in the browser.

Using the Prototype

Recommended Browsers

View the prototype that you export to your iOS device in the iCab Mobile browser, because it allows for full-screen viewing and offline Web caching. This makes for a reliable and more realistic experience when showing the work to clients.

To view and test the prototype on a desktop computer, Apple’s Safari browser (available for both Mac and Windows) is recommended.

Keep in mind that, from time to time, the browser on a desktop computer might render things slightly different than on an iOS device (in one case, my computer’s browser displayed a slide-in transition, whereas on the iPad a fade was displayed). In such instances, trust iOS’ rendering because that is what TAP was designed for.

Setting Up iCab Mobile’s Full-Screen Mode

Download iCab Mobile from the Appstore, and launch it.

iCab Mobile Icon

Below is an example of a full-screen set-up. To get there, tap the settings button (i.e. the gear icon in the upper-right corner).

iCab Settings Icon
iCab settings

iCab Full Sceen IconSetup
Configure the full-screen heads-up display (HUD) settings to match this screenshot, so that you can exit full screen without being distracted by extraneous buttons. You can experiment on the placement of the button to exit full screen if it is often accidentally pressed when users are testing the design.

Then, tap the button for the full-screen icon. Remove all buttons except for “Exit” (which returns the user to non-full-screen mode). To do this, click on the icon slot that you wish to change, and select none (represented by a -/- ) from the list of options to make that icon blank. Also, turn transparency all the way down to make this control as unobtrusive as possible.

Set Up Offline Viewing

If you want a bulletproof plan to show your prototype regardless of whether there is Wi-Fi or 3G access, then set up the HTML iOS prototype for offline viewing by saving it in iCab Mobile’s cache.

First, click the settings icon (the gear icon in the upper-right corner).

iCab Settings Icon

“General Settings” will automatically be selected. In the right pane, scroll down to the last section, and set the “Disk Cache” to 100 MB. This should be enough space for even the largest of prototypes (if this is the first time you are using iCab, click “Delete Disk Cache”).

iCab Offline Settings
To set up iCab to for offline viewing, turn offline mode to “On,” and set the disk cache to the highest amount, which is 100 MB.

Now that the cache has been set up, you’ll need to create an offline bookmark to save the iOS prototype to the cache. Enter the URL of the page that you would like to bookmark, and then click on the “Send to” icon (i.e. the box with an arrow coming out of it). Next, select “Add to bookmarks,” and turn on “Offline bookmarks” in the pop-over.

iCab - create offline bookmark
To create an offline bookmark, turn on the “Offline bookmark” option.

Finally, click “Save.”

Viewing Your Bookmarks Offline

By turning on offline mode, iCab Mobile will look for the cached offline bookmark, instead of going to the original online URL of your prototype. You need to explicitly switch on offline mode in the browser only when an active Internet connection is available but you still want to load the Web page offline from the cache. However, if no Internet connection is available (for instance, if airplane mode is on or no Wi-Fi or cellular connection is available), then iCab will automatically use offline mode, so you do not need to explicitly switch it on.

Open an Offline Bookmark

Tap the bookmarks icon to open the bookmarks pop-over. Then, click the “Offline” button next to the link that you want to browse offline. (Don’t click the title of the bookmark, because that would instruct the browser to open it from an online connection, not from the cache.)

iCab - load offline page
Tapping the title of the bookmark will send you to the online version of the bookmark. Tapping the “Offline” button will send you to the saved offline version of your website via the cache.

When using offline mode, remember to set the cache to a larger size in the settings (bigger is better). If you add an offline bookmark, it will be saved to the cache; so, if you make changes or bug fixes to your website, remember to delete the cache and add the offline bookmark again so that the updated version will be loaded!

Conclusion

There are many ways to create wireframes, click-throughs and prototypes. In the end, what matters is that the process of creation is fast and accurate and that the output is of a high enough fidelity to generate the appropriate level of feedback.

Having tried many programs to design iOS prototypes, I have found that using Adobe Fireworks in conjunction with TAP is the most efficient and effective method available. In Fireworks, I can quickly and easily draw whatever I’ve dreamed up, and the pages, shared layers, symbols and styles ensure that my prototype works as a cohesive system that can be easily updated when needed.

Then, using TAP, I can bring my wireframes to life on an iOS device, using animated transitions initiated by gestures.

If you haven’t yet, try Adobe Fireworks together with TAP. The process of using Fireworks and TAP is so simple and fast that you will find you get feedback earlier in the design process and iterate with less effort than ever before, resulting in stronger and more refined designs.

Further Resources

The following articles, tutorials and video tutorials will help you get started with Adobe Fireworks.

General articles about Adobe Fireworks:

How Adobe Fireworks is used at Cooper (my place of work):

Articles about Fireworks layers, pages and objects:

Articles about Fireworks symbols and styles:

Articles about prototyping and wireframing with Fireworks:

Questions?

I know this has been a lengthy read, but hopefully fun, too.

Still, it’s possible that I’ve missed some things, so I’d love to answer any questions you may have or hear your feedback about this technique of prototyping with Fireworks and TAP for iOS.

(mb al)


© Shlomo Goltz for Smashing Magazine, 2013.

Smashing Magazine

Mechanism Of Action And Effects: Designing Great Feedback Loops


  

The products we build are full of feedback loops, whether we know it or not. People who study human behavior agree that feedback loops play a critical role in what we do. From biofeedback to the quantified self, designers and psychologists alike are discovering the real power that these cyclical interactions play in shaping our day-to-day choices. Designing for behavior change can increase user engagement, create business value and improve lives.

Whatever you’re designing, it probably involves feedback. Designing that feedback to be as effective as possible can mean the difference between a successful and failed product. This article discusses how to influence behavior by designing well-crafted feedback loops.

What They Are, And Where They Live

Feedback loops consist of a few simple steps:

  1. A person takes an action,
  2. The action has one or more effects,
  3. The important effects of this action are presented back to the person,
  4. This loop is repeated regularly.

Feedback Loops Diagram

There are many natural feedback loops. They reveal to people whether they are making good or bad choices, and people learn from them. If someone eats something bad, they get sick. If they eat something good, it is delicious. If a person is nice to someone, and that someone responds in kind, the person feels good. If someone damages their body, it hurts. The brain has systems of reward and punishment that support basic survival.

There are now many man-made examples of these as well. People take tests on their knowledge and receive a grade. They post a status update to Facebook and get rewarded when people like or comment on it. “Post more stuff like this,” the feedback seems to say.

So, let’s dive into improving our own feedback loops!

Discover Your Product’s Basic Feedback Loops

The first step is to identify your product’s feedback loops. What are the fundamental repeated behaviors that your users engage in?

Many social apps share the following basic loop: a user posts something, people see it, people click a button to “like” it, and the likes are presented back to the user. Email has a strong, simple loop: log in, see new emails, deal with the emails.


The social apps Instagram, Facebook and Twitter all have feedback loops.

But they can also be harder to see. Yelp has built great feedback loops around local reviews. A restaurant provides food and services, and better services lead to better reviews. Meanwhile, customers dine in and leave reviews, which themselves are reviewed in turn by other people (see those “Useful,” “Funny” and “Cool” buttons). Some people who leave enough reviews can get invited to special parties and more (“Yelp Elites”). These loops are purposefully designed: they drive people to engage with the website and to contribute content that is valuable to Yelp’s business.

Yelp Profile Screenshot
My Yelp profile, with prominent feedback.

Look for patterns of repeated behavior, and list the ones you find. These behaviors could span time, digital and physical space, channels of communication, and even different people. Look closely at user actions that trigger a notification sent to them or others. Investigate places where users communicate with each other or with employees, either directly or indirectly. These areas are fertile ground for feedback loops, and you should be able to draw up a robust list without much effort.

Understand How These Loops Are Broken, And Fix Them

Now that you have a list of areas that can be improved, identify the most important or common ones in your product. They can be improved in any one of these aspects:

  1. Speed,
  2. Measurability,
  3. Context,
  4. Connection to motivations.

1. Speed

“It’s too slow!”

Problem: The longer it takes for feedback to arrive, the less it will influence future decisions.

In operant conditioning, this is called “immediacy,” and it’s also related to “hyperbolic discounting.”

For example, when the user of a financial website makes an investment, seeing the outcomes of that investment could take years. Without any simulation of what their investment’s growth might look like, they have little emotional material to support that decision.

Stopwatch

Solution: Tighten the feedback loop by presenting effects as soon as possible. This could entail revealing real effects, or simply simulating them. As long as they’re grounded in reality, they will have influence. Even presenting simulated feedback right before someone makes a decision is effective. Knowing that an investment will likely earn them $1,000 will help the user feel good about making that decision.

On ReadyForZero, our tool to help people organize and pay off debt, we enable the user to simulate the impact of different payment plans in real time, instantly revealing an outcome that could happen years from now.


ReadyForZero simulates the impact of a payment plan in real time.

Smartphone push notifications have also gone a long way to giving immediate feedback. Posting something to Instagram, Facebook, Twitter and so on and then hearing one’s phone buzz with social feedback within minutes is a powerful loop. Always be sure to use push notifications when appropriate.

Credit cards provide a physical example of how delayed feedback can make for a dark pattern that drives harmful behavior. These cards have made banks huge amounts of money by alleviating a painful loop: pulling out your wallet and handing over your hard-earned cash. The more cash you spend, the more it disappears from your wallet. Soon, you are forced to go to the bank to get more, making you physically see and feel the effects of spending. Credit cards effectively delay the feedback on how much you spend until you bother to check the balance or are sent a bill at the end of the month. Even then, you have the option of delaying payment of the full balance (accruing interest in the meantime). This makes sliding into debt very easy.

2. Measurability

“How does it compare?”

Problem: Comparing vague, unquantifiable feedback to other factors in order to make an informed decision is too difficult.

Take nutrition, a notoriously vague problem space for feedback. How do people know whether they’re eating well? If they’ve heard that the thing they’re eating is unhealthy, how unhealthy is it? If the feedback is presented in some quantifiable way that relates to reality, it will be easier to understand and the person’s decisions will be more informed. Nutrition labels have made the effects of food more measurable. Now, someone can actually quantify the benefit of eating an apple, and the problem with eating a pile of bacon.

Solution: As nutrition labels have done for food, give quantifiable feedback to users. Use visual comparisons as well, when possible. The human brain is great with tangible comparisons between the sizes, locations and other variables of objects. Read up on the framing effect as well as anchoring for more on the psychological reasons for why this works.

Klout is attempting to make social influence measurable with its Klout score. It demonstrates the power of making things measurable, enabling users to objectively compare the online social influence of different people. It also highlights the risks of creating metrics where there were none before. The Klout score is interesting, but it’s based on a limited set of social signals, such as followers, likes, replies, retweets and comments. Metrics must be believable and must accurately reflect reality, a hard thing to accomplish with social influence.

Klout Profile Screenshot
My Klout score changes over time based on social interactions.

A lesson we’ve learned about measurability at ReadyForZero is to use numbers that are at a scale that people deal with in real life, typically up to 100. Telling a user that their debt will cost them $150,000 in interest means almost nothing to them other than “a lot of money” and isn’t that useful. Instead, we focus on how much someone’s debt costs them in interest every day, because this number tends to be in the $1 to $30 range and is comparable to many things they purchase daily, such as coffee and meals. Feeling good about their progress has helped our users significantly.

3. Context

“What does it mean?”

Problem: Feedback presented without the context of a larger goal isn’t as effective.

Saving some extra money can make someone feel good. But saving towards a goal is more meaningful. “This deposit of $500 has put me one third of the way towards my vacation.” Providing context for the feedback not only creates a signpost by which to measure progress, but actually frames the way people think about a problem. For example, “You’ve spent $1,200 this week” is a very different way to frame one’s finances than “You’ve spent $1,200 of your budgeted $700 this week,” even though they represent the same data.

Solution: Frame effects in the context of user goals. How much closer to or further from a goal has this action taken the user? On ReadyForZero, we show the amount of time and interest saved by making a big payment towards a debt, and the amount lost by buying things on a credit card.

This is a form of “anchoring.” By showing a desired goal, you’ve set the anchor by which the user can then evaluate their current situation. If they have not yet reached the goal, they’ll feel the tension of wanting to reach it.

The Nike+ Fuelband, along with many other quantified-self activity-tracking devices, explicitly creates feedback loops and goals around user behavior where there were none before. The user’s physical activity is tracked and reported throughout the day, compared to goals, and shared online. Note the strong use of progress bars, both on the watch and in the app, which communicate how close the user is to reaching their daily goal.


The Nike+ Fuelband shows daily activity relative to goals.

4. Motivations

“I don’t care.”

Problem: Feedback that isn’t connected to the user’s true motivations doesn’t work sustainably.

“Gamified” feedback loops are able to make an impact, but points and badges that don’t connect to anything meaningful won’t last. People don’t care about points; they care about things such as health, happiness, friendship and wealth. Right now, which would you rather have: 30 Foursquare points, 30 likes on your next Facebook update, 30 extra minutes in your day or $30? The answers may vary, but I’ll bet the Foursquare points would be last on the list for everyone.

Solution: Discover what your users care about, give them the ability to reach those goals, and present feedback connected to that. Social rewards, such as comments on our thoughts and photos, connect to the need for human relationships. Feeling fit and looking great connects to the goal of being healthy. Money connects to the many things people spend it on.

On ReadyForZero, we help people pay down their debt by showing them a number of bits of important feedback. First, we tangibly show the progress that a potential payment would make towards their goal on a progress bar. The visual connection enhances the feeling of achievement. Secondly, we tell them the long-term implications of that payment in terms of interest and time saved.


ReadyForZero shows the impact of a payment to credit-card debt, including real time and money saved.

Fully grasping what your users’ motivations are can be difficult. There are many theories about how motivation works, each with implications for design. A useful framework is the theory of self determination, which posits that people who have most of their basic needs met can begin to look for autonomy, relatedness and competence. The theory is that these motivations arise not from the outside world, but from inside, and are more powerful. Theory aside, however, the tried and true approach of speaking candidly and in depth with your users will reveal what they truly care about.

Two Things To Remember

With these categories in focus, you’re on your way to designing better feedback loops. However, keep two things in mind as you go.

1. Measure Your Success

Now that you’ve identified your areas for improvement and made changes to them based on our criteria, it’s important to measure the outcomes of these changes using analytics and user research. As stated, you can’t improve what you can’t measure.

Analytics and research are, in fact, your own internal feedback loop as a designer. Consider the key metrics to track and report, how often they are reported, and in what context. The design of this feedback loop will affect how you respond to user behavior, and it’s important that your team is optimizing for the right things.

2. Be Ethical

Finally, throughout the process, evaluate the ethics involved in each decision. The power of behavioral techniques should always inspire a discussion within your team as well as within yourself. Are you designing a health improvement app, a utility or a slot machine? Which of these is acceptable? Taking responsibility for influencing behavior requires a strong moral compass. Products that have taken the low road have been both successful and harmful.

Zynga has created a business model around extremely effective feedback loops, but the values informing many of these loops have been routinely criticized as being unethical. For example, Zynga uses progress bars, goals, levels and social pressures very effectively to monetize its signature game, Farmville. However, such games arguably succeed at the expense of the user’s time, cash and creativity. They focus on achieving business goals by manipulating user emotions.


Cityville, another popular Zynga game, uses progress bars, levels and cleverly timed loops to drive engagement.

Defining “fun” is beyond the scope of this article, but the clever timing of cash-based advances in gameplay is clearly designed for profit rather than for the player’s experience. Read about the fascinating Cow Clicker saga for an amusing critique of this model.

For a more rational approach to designing ethically, review Stephen Anderson’s guidelines, which take a deeper look at how to calibrate your moral compass.

In general, use the golden rule, and try to make the world a better place for everyone.

In Summary

Design can be used to nudge behavior, and great feedback loops are a vital piece of pulling it off. Assist your users in understanding and achieving their goals by continually optimizing your feedback loops. Focus on making them fast, meaningful, quantified and contextual, and your users will thank you for improving their lives.

(al)


© Loren Baxter for Smashing Magazine, 2013.

Smashing Magazine

Web Content Optimization: Setting Weights And Styles With The @font-face Declaration


  

If people are on your website, they’re probably either skimming quickly, looking for something, or they’ve found what they’re looking for and want to read it as easily as possible. Either way, keeping text readable will help them achieve their goal.

Bold and Italic Help to Organize Content

A few months ago, I wrote an article on “Avoiding Faux Weights and Styles with Google Web Fonts.” I ended the article by showing that weights and styles are an important UX element when setting text. Bold and italic forms of a font help people to skim your website. They add emphasis — both strong and subtle — that can help visitors understand the organization of content before even starting to read it.

1_organize_text
Weights and styles are an important UX element. Bold and italic help readers to see structure and to skim the text more efficiently (left). The same text without bold or italic (right) feels more like a narrative.

In this article, we’ll start where we left off. Because weights and styles help our visitors to read our content, we should make sure they work! And getting weights and styles to work correctly using the @font-face declaration can be a bit crazy-making. Let’s look at two popular approaches to setting weights and styles with the @font-face declaration. I’ll show you why they are not the best solutions, and show you a third more effective approach to follow.

Unique Font-Family Names, Normal Weights And Styles

If you’ve used one of FontSquirrel’s amazing @font-face kits, then you’re familiar with this approach to setting weights and styles. The CSS provided in every kit uses a unique font-family name for each weight and style, and sets the weight and style in the @font-face declaration to normal.

For example, the syntax for Ubuntu Italic and Ubuntu Bold looks like this:

@font-face {
   font-family: 'UbuntuItalic';
      src: url('Ubuntu-RI-webfont.eot');
      src: url('Ubuntu-RI-webfont.eot?#iefix') format('embedded-opentype'),
           url('Ubuntu-RI-webfont.woff') format('woff'),
           url('Ubuntu-RI-webfont.ttf') format('truetype'),
           url('Ubuntu-RI-webfont.svg#UbuntuItalic') format('svg');
   font-weight: normal;
   font-style: normal;
}

@font-face {
   font-family: 'UbuntuBold';
      src: url('Ubuntu-B-webfont.eot');
      src: url('Ubuntu-B-webfont.eot?#iefix') format('embedded-opentype'),
           url('Ubuntu-B-webfont.woff') format('woff'),
           url('Ubuntu-B-webfont.ttf') format('truetype'),
           url('Ubuntu-B-webfont.svg#UbuntuBold') format('svg');
   font-weight: normal;
   font-style: normal;
}

Notice that the font-family names are unique, with each font-family name accessing the appropriate Web font files. For example, UbuntuItalic accesses Ubuntu-RI-webfont.woff, while UbuntuBold accesses Ubuntu-B-webfont.woff.

Also, notice that the font-weight and font-style for both @font-face declarations are set to normal.

Styling Text Using This Method

To style text using this method, use the appropriate font-family name, and keep all weights and styles set to normal. For example, the Regular, Regular Italic, Bold and Bold Italic headings below are set with classes. The classes are styled like so:

.u400 {
   font-family: 'UbuntuRegular', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

.u400i {
   font-family: 'UbuntuRegularItalic', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

.u700 {
   font-family: 'UbuntuBold', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

.u700i {
   font-family: 'UbuntuBoldItalic', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

2_unique_font-families
Ubuntu Regular, Italic, Bold and Bold Italic on Windows 7 in Internet Explorer 8 (top) and on Mac OS X in Chrome 23 (bottom). Unique font-family names with normal weights and styles (á la FontSquirrel) work fine.

Make Sure the Weights and Styles Match!

Because the weights and styles are set to normal in the @font-face declarations, keeping the weights and styles set to normal when styling the text is important. Otherwise, the bolds may double-bold (some browsers will add a bold weight to the already bold Web font), and the italics may double-italic (some browsers will add an italic style to the already italic Web font).

For example, let’s say we incorrectly set the font-style to italic and the font-weight to 700 (bold) in our corresponding classes:

.u400 {
   font-family: 'UbuntuRegular', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

.u400i {
   font-family: 'UbuntuRegularItalic', arial, sans-serif;
   font-weight: normal;
   font-style: italic;
}

.u700 {
   font-family: 'UbuntuBold', arial, sans-serif;
   font-weight: 700;
   font-style: normal;
}

.u700i {
   font-family: 'UbuntuBoldItalic', arial, sans-serif;
   font-weight: 700;
   font-style: italic;
}

The fonts will render incorrectly in Mac OS X browsers and on iPad Safari browsers.

3_unique_double-bold
When using normal weights and styles in the @font-face declaration, give text elements normal weights and styles, too. Otherwise, your text may end up with a double-bold and double-italic. If you set text elements as bold or italic, then Ubuntu Italic, Bold and Bold Italic won’t double-bold or double-italic on Windows 7 in Internet Explorer 8 (top). But look at what happens on Mac OS X in Firefox 17 and on iPad 3 with iOS 5.1 in Safari (bottom) — yikes!

Using and Elements

While and can be styled to communicate emphasis and importance in a variety of ways, they are often used in their default forms: with set to italic text and set to bold text.

For example, the paragraph below is styled like so:

p {
   font-family: 'UbuntuRegular', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

And the and elements are left in their default states:

em {
   font-style: italic;
}

strong {
   font-weight: bold;
}

4_unique_em_strong_faux
Applying and in their default states results in faux italic and faux bold.

The result is a faux italic and a faux bold. Why? Because the paragraph is set to Ubuntu Regular, with the weight and style set to normal. When the element is applied, the text remains Ubuntu Regular but is slanted to look like it’s italic. Notice the angular “e” and the double-story “a.” When the element is applied, the text remains Ubuntu Regular but is stretched to look like it’s bold. Notice the letter “e” is no longer monoline — the sides of the letter look thicker than the top and bottom of the letter.

We can fix this problem by making sure the and elements use the correct font-family name. For example, the paragraph below continues to be styled like so:

p {
   font-family: 'UbuntuRegular', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

And the  and elements are styled to use the correct corresponding font-family names:

em {
   font-family: 'UbuntuRegularItalic', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

strong {
   font-family: 'UbuntuBold', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

Notice that the font-weight and font-style for both and are set to normal. This is counterintuitive, but necessary so that the text doesn’t end up with a double-italic or a double-bold.

5_unique_em_strong_fixed
Using the correct font-family names — and setting weights and styles to normal — results in true italic and true bold.

The result is a true italic and true bold. Why? Because while the paragraph is set to Ubuntu Regular, the element is set to Ubuntu Italic and the element is set to Ubuntu Bold — and all weights and styles are set to normal.

Problem: If the Fallback Font Loads, Weights and Styles Will Be Lost

While purposely stripping out weights and styles is counterintuitive, using a unique font-family name and normal weights and styles does work — as long as the Web font loads.

If the fallback font loads, then all bolds and italics will be lost — because we had set all weights and styles to normal — thus making it harder for readers to see the structure of your website’s content and making it harder for them to skim the text.

6_unique_fontfail
If the Web font doesn’t load, then the fallback font (here, Times New Roman) will load with a normal weight and style — undermining hierarchy and readability. Remember, we had set all weights and styles to normal when we styled the elements!

The Short Version

Using unique font-family names combined with setting font-weight and font-style to normal is unforgiving. Mismatching weights and styles could easily result in either faux italic and faux bold or double-italic and double-bold. If the Web font doesn’t load, then the result will be no italic or bold! So, this approach to setting weights and styles using the @font-face declaration isn’t the best solution.

Style Linking

Another way to set weights and styles is to use the same font-family name multiple times, setting the weights and styles in each @font-face declaration to match the weight and style of the Web font file being accessed. This approach is called style linking.

For example, using style linking, the syntax for Ubuntu Italic and Ubuntu Bold would look like this:

@font-face {
   font-family: 'Ubuntu';
      src: url('Ubuntu-RI-webfont.eot');
      src: url('Ubuntu-RI-webfont.eot?#iefix') format('embedded-opentype'),
           url('Ubuntu-RI-webfont.woff') format('woff'),
           url('Ubuntu-RI-webfont.ttf') format('truetype'),
           url('Ubuntu-RI-webfont.svg#UbuntuItalic') format('svg');
   font-weight: 400;
   font-style: italic;
}

@font-face {
   font-family: 'Ubuntu';
      src: url('Ubuntu-B-webfont.eot');
      src: url('Ubuntu-B-webfont.eot?#iefix') format('embedded-opentype'),
           url('Ubuntu-B-webfont.woff') format('woff'),
           url('Ubuntu-B-webfont.ttf') format('truetype'),
           url('Ubuntu-B-webfont.svg#UbuntuBold') format('svg');
   font-weight: 700;
   font-style: normal;
}

Notice that the font-family names are the same, regardless of what Web font file is being accessed. For example, Ubuntu accesses Ubuntu-RI-webfont.woff, and Ubuntu also accesses Ubuntu-B-webfont.woff. How does that work?

Notice that the font-weight and font-style for each @font-face declaration is set to match the weight and style of the Web font file being accessed. The Ubuntu that accesses the italic Web font file has font-style: italic. The Ubuntu that accesses the bold Web font file has font-weight: 700.

In this method, the weights and styles in the @font-face declarations act as “markers.” When a browser encounters those weights and styles elsewhere in the CSS, it knows which @font-family declaration to use and which Web font files to access.

Styling Text Using Style Linking

To style text with this method, use the same font family for all versions of the font. Set weights and styles to trigger the correct Web font files that the browser should access. If you want the italic version of the font, make sure to set font-style: italic. For example, the Regular, Regular Italic, Bold and Bold Italic headings below are set with classes. The classes are styled like so:

.u400 {
   font-family: 'Ubuntu', arial, sans-serif;
   font-weight: 400;
   font-style: normal;
}

.u400i {
   font-family: 'Ubuntu', arial, sans-serif;
   font-weight: 400;
   font-style: italic;
}

.u700 {
   font-family: 'Ubuntu', arial, sans-serif;
   font-weight: 700;
   font-style: normal;
}

.u700i {
   font-family: 'Ubuntu', arial, sans-serif;
   font-weight: 700;
   font-style: italic;
}

7_style-linking
Ubuntu Regular, Italic, Bold and Bold Italic on Windows 7 in Internet Explorer 8 (top) and on Mac OS X in Chrome 23 (bottom). Using style linking to set weight and style appears to work fine.

Again, Make Sure the Weights and Styles Match!

Because weight and style are used to “trigger” the correct @font-face declaration, setting weights and styles to match those used in the @font-face declarations is important. As a bonus, when default rules for weights and styles are applied by browsers — like italic for and bold for — then the correct fonts will automatically load (as long as your font has a bold and italic version), because the default rules will also trigger the correct @font-face declaration.

8_style-linking_em_strong
When default rules for weights and styles are applied by browsers — like italic for and bold for — then the correct fonts will automatically load (as long as your font has a bold and italic version). Again, using style linking to set weight and style appears to work fine.

Bonus: If the Fallback Font Loads, Weights and Styles Will Be Retained

Unlike the first approach, setting weights and styles with style linking means that weights and styles will be retained even when the Web font fails to load. Why? Because all weights and styles were set correctly (for example, not normal) when styling the text.

Note: If the Web font doesn’t load, then the fallback font (here, Times New Roman) will still provide hierarchy — bolds and italics will remain intact. Remember, we set all weights and styles to match the Web fonts when we styled the elements!

But style linking has its own problems…

Problem: Internet Explorer 7 and 8 Can Only Apply Up to Four Weights and Styles to a Single Font-Family Name

Style linking works — as long as you’re not using more than four weights and styles (and as long as the person reading your Web page isn’t the one of the one in eight people who still use Internet Explorer (IE) 7 or 8). If you use more than four weights and styles on the website, then IE 7 and 8 will convert all light and medium weights to normal, and all black and heavy weights to bold — so, you’ll lose some of your carefully set text.

10_style-linking_fail
IE 7 and 8 can’t apply more than four weights and styles to a single font-family name. Ubuntu has eight weights and styles. If you used all eight with the font-family name Ubuntu, then the Light, Light Italic, Medium and Medium Italic would convert to Regular and Regular Italic.

Problem: Crashes Browsers on BlackBerry and iPad 1

No matter how well your fonts load, if the page crashes the browser, people won’t be able to see your content! And as of this writing, Web pages that use style linking crash BlackBerry 9900 browsers on a regular basis. They also crash iPad 1 browsers 100% of the time.

The Short Version

Using style linking appears to be more forgiving. It greatly reduces the potential for setting text that is faux italic and faux bold, or double-italic and double-bold. In addition, if the Web font doesn’t load, the text will retain both style and weight. But if you’re using more than four weights and styles, then text won’t render properly in IE 7 and 8. In addition, style linking crashes the browsers on BlackBerry and iPad 1 devices. So, this approach to setting weights and styles using the @font-face declaration isn’t the best solution at this time (although the future — when IE 7 and 8, BlackBerry 9900 and iPad 1 are all defunct — looks bright!).

Unique Font-Family Names, Matching Weights And Styles

A third — and currently the most effective — way to set weights and styles is to merge the first two methods. If you’ve used FontDeck for Web fonts, then you’ll be familiar with this approach.

Use the unique font-family names — which allows IE to show all of the weights and styles you need. Also, use matching weights and styles (for example, do not set weights and styles to normal), which will keep the weights and styles intact should the Web font fail.

For example, the syntax for Ubuntu Italic and Ubuntu Bold would like this:

@font-face {
   font-family: 'UbuntuItalic';
      src: url('Ubuntu-RI-webfont.eot');
      src: url('Ubuntu-RI-webfont.eot?#iefix') format('embedded-opentype'),
           url('Ubuntu-RI-webfont.woff') format('woff'),
           url('Ubuntu-RI-webfont.ttf') format('truetype'),
           url('Ubuntu-RI-webfont.svg#UbuntuItalic') format('svg');
   font-weight: 400;
   font-style: italic;
}

@font-face {
   font-family: 'UbuntuBold';
      src: url('Ubuntu-B-webfont.eot');
      src: url('Ubuntu-B-webfont.eot?#iefix') format('embedded-opentype'),
           url('Ubuntu-B-webfont.woff') format('woff'),
           url('Ubuntu-B-webfont.ttf') format('truetype'),
           url('Ubuntu-B-webfont.svg#UbuntuBold') format('svg');
   font-weight: 700;
   font-style: normal;
}

Notice that the font-family names are unique, with each font-family name accessing the appropriate Web font files. For example, UbuntuItalic accesses Ubuntu-RI-webfont.woff, while UbuntuBold accesses Ubuntu-B-webfont.woff.

Also, notice the weight and style: The font-weight and font-style for each @font-face declaration is set to match the weight and style of the Web font file being accessed. The UbuntuItalic that accesses the italic Web font file has font-style: italic. The UbuntuBold that accesses the bold Web font file has font-weight: 700.

Styling Text Using the Combined Method

To style text with this method, use the unique font-family names, and set weights and styles to match those used in the @font-face declarations. For example, the Light, Light Italic, Regular, Regular Italic, Medium, Medium Italic, Bold and Bold Italic headings below are set with classes. The classes are styled like so:

.u300 {
   font-family: 'UbuntuLight', arial, sans-serif;
   font-weight: 300;
   font-style: normal;
}

.u300i {
   font-family: 'UbuntuLightItalic', arial, sans-serif;
   font-weight: 300;
   font-style: italic;
}

.u400 {
   font-family: 'UbuntuRegular', arial, sans-serif;
   font-weight: 400;
   font-style: normal;
}

.u400i {
   font-family: 'UbuntuRegularItalic', arial, sans-serif;
   font-weight: 400;
   font-style: italic;
}

.u700 {
   font-family: 'UbuntuMedium', arial, sans-serif;
   font-weight: 500;
   font-style: normal;
}

.u700i {
   font-family: 'UbuntuMediumItalic', arial, sans-serif;
   font-weight: 500;
   font-style: italic;
}

.u900 {
   font-family: 'UbuntuBold', arial, sans-serif;
   font-weight: 700;
   font-style: normal;
}

.u900i {
   font-family: 'UbuntuBoldItalic', arial, sans-serif;
   font-weight: 700;
   font-style: italic;
}

11_unique_style-linking
By combining unique font-family names with matching weights and styles, all eight weights and styles of Ubuntu will work — even on Windows 7 in IE 8. And BlackBerry and iPad 1 browsers won’t crash.

Again, Make Sure the Weights and Styles Match!

Although using unique font-family names means we no longer need the weights and styles to “trigger” the correct @font-face declaration, setting all weights and styles to match is important. Applying weights and styles to text elements will keep them intact in case the Web font fails. Also, because the weights and styles match, the text won’t end up with either a double-bold or double-italic, or a faux bold or faux italic.

Problem: Using and Elements

Using unique font-family names brings back an earlier problem: getting and elements to work properly. Default styling on these elements will result in faux italic and faux bold text.

For example, the three paragraphs below are styled like so:

p.light {
   font-family: 'UbuntuLight', arial, sans-serif;
   font-weight: 300;
   font-style: normal;
}

p {
   font-family: 'UbuntuRegular', arial, sans-serif;
   font-weight: normal;
   font-style: normal;
}

p.medium {
   font-family: 'UbuntuMedium', arial, sans-serif;
   font-weight: 500;
   font-style: normal;
}

And the and elements are left in their default states:

em {
   font-style: italic;
}

strong {
   font-weight: bold;
}

12_unique_style-linking_EmStrong_default
Applying and in their default states will result in faux italic and (usually) faux bold.

The result is a faux italic and a faux bold (when it’s applied). Why? Because we’re using unique font-family names. Let’s look at the middle paragraph. It’s set to Ubuntu Regular, with weight and style set to match (weight: normal and style: normal). When the element is applied, the text remains Ubuntu Regular but is slanted to look like it’s italic. When the element is applied, the text remains Ubuntu Regular but is stretched to look like it’s bold.

We can fix the bold text by making sure the element uses the correct font-family name, weight and style:

strong {
   font-family: 'UbuntuBold', arial, sans-serif;
   font-weight: 700;
   font-style: normal;
} 

The  is a bit more difficult to fix. We can set it to Ubuntu Regular Italic and use the matching weight and style:

em {
   font-family: 'UbuntuRegularItalic', arial, sans-serif;
   font-weight: 400;
   font-style: italic;
}

13_unique_style-linking_EmStrong_set
Setting to UbuntuRegularItalic and to UbuntuBold will result in an italic that’s too heavy for light text and too light for medium text.

The result is a bold and italic that are consistent throughout, regardless of the weight of the paragraph text. This may be fine for the element, but the element looks a bit out of place on both the light and medium text.

The only way to fix this is to create a variety of classes for the element, like so:

em {
   font-family: 'UbuntuRegularItalic', arial, sans-serif;
   font-weight: 400;
   font-style: italic;
}

em.light {
   font-family: 'UbuntuLightItalic', arial, sans-serif;
   font-weight: 300;
   font-style: italic;
}

em.medium {
   font-family: 'UbuntuMediumItalic', arial, sans-serif;
   font-weight: 500;
   font-style: italic;
}

14_unique_style-linking_Em3Strong_set
Creating three versions of the element (em, em.light, em.medium) will result in italics that “match” the weight of the text.

This will result in italics that match the weight of the text in each paragraph. This creates much better hierarchy, but it undermines the beauty of cascading style sheets and the simplicity of using a single element.

Bonus: If the Fallback Font Loads, Weights and Styles Will Be Retained

Setting all weights and styles correctly (for example, not normal) when styling the text means that basic weights and styles will be retained even if the Web font doesn’t load.

15_unique_style-linking_fontfail
If the Web font doesn’t load, then the fallback font (here, Times New Roman) will still provide hierarchy — bolds and italics will remain intact. But because fallback fonts don’t usually have “extra” weights (such as Light, Medium and Black), some weights will revert to Normal and Bold.

The Short Version

Using unique font-family names and setting weights and styles to match (for example, not setting them to normal) is the most effective method of getting weights and styles to work with the @font-face declaration. An extra step is required (i.e. setting and using unique font-family names — even with elements such as and ) to avoid faux italic and faux bold, but the solution does reduce the potential for double-italic and double-bold text. In addition, if the Web font doesn’t load, then the text will retain both style and weight. Finally, text will render properly in IE 7 and 8 (even if you’re using more than four weights and styles), and your pages won’t crash the browsers on BlackBerry 9900 and iPad 1 devices.

Make Sure Your Weights And Styles Work

Weights and styles help visitors read the content on your website. So, make sure your weights and styles load correctly — whether for IE 8, Chrome, Mac OS X Firefox or an iPad and whether or not the Web font loads correctly (or visitors see a fallback font).

When choosing which method to use for your website, ask yourself two questions:

  1. Will I be using more than four weights and styles on the website?
  2. Are BlackBerry and iPad 1 users part of my target audience?

If the answer to both questions is “no,” then go ahead and use style linking. It’s elegant and forgiving.

If the answer to either question is “yes,” then use the combined method. Currently, the only way to make sure your weights and styles work cross-browser is to use unique font-family names in conjunction with matching weights and styles (and, of course, to make sure your font has a bold and italic version). This might sound like a chore, requiring extra care and typing (UbuntuRegularItalic is longer to type than Ubuntu, after all), but as with most typographic details, the best results take time and effort. Even Typekit, which uses JavaScript to handle the intricacies of Web fonts, requires variation-specific font-family names to support older versions of IE.

Once IE 7 and 8, BlackBerry 9900 browsers and the iPad 1 are defunct, using style linking alone should be enough to get the job done. But as of 28 January 2013, StatCounter reports that IE 7 and 8 alone were used for 12.3% of the 45 billion page views collected from November 2012 to January 2013. Information on mobile browsers is not clear, but a minimum of 1 in 8 visitors still need us to go the extra mile. So, for now, we’ve got some extra typing to do.

Further Resources

(al)


© Laura Franz for Smashing Magazine, 2013.

Smashing Magazine

Responsive Web Design: Planning For The Future


  

When considering a mobile Web strategy and weighing responsive Web design against a separate mobile website, the most important metric is how functional the website is for the user. This goes beyond better content organization for smaller screens. Mobile (and desktop) websites should be easily found, easily shared, fast loading, easy to maintain and easy to build on.

If we keep that in mind, considering where the Web is today and where it looks to be going, there are many compelling arguments for responsive Web design.

Setting The Stage

Consider something as simple as Google Doodles. These small updates create major buzz for Google, and they offer a bit of surprise on an almost daily basis. Then consider how websites like Facebook update their code base twice a day. Both cases hint at a future where users will expect content and features to evolve faster than ever.

On top of new content demands, people are also sharing information more than ever, creating the need for centralized, up-to-date content and a reliable way to access that content.

Unfortunately, those aren’t the only challenges created by this evolving Internet. Those problems can, however, be solved using responsive Web design.

Before I get into the specifics of why I believe responsive is better now and in the future, I’d like to clear one thing up.

The Content Myth

To frame this whole debate, it’s important to forget an old myth. It’s the belief that content should be restricted, dumbed-down or eliminated for mobile users based on their goals and intent.

Up until now, limiting content made some sense. Especially in the early days of the modern mobile Web browser. Today, however, it is widely accepted that we don’t know anything about our users’ goals based on which device they are using. Users need and expect full functionality on their mobile device, because they could be using it anywhere, for any reason. 28% of American adult smartphone owners now access the Internet mostly on their mobile device. That means that many of your users literally require all of the same functionality on mobile that they would otherwise get on a desktop.

We can’t eliminate content or functionality, but we also can’t show everything at once on a small screen. This means we need to redesign and reorganize content into smaller “views” and hide or hint at secondary content in smart ways. This isn’t necessarily easy, but it’s necessary.

Quartz's menu is hidden and hinted at on small screens.
Quartz’s menu is hidden and hinted at on small screens. Larger view.

Now that we know the facts — that we have to restructure content, but not eliminate it — there are two ways to achieve this. One is with responsive Web design, and the other is a separate, mobile-focused website.

Consistent URL Structure

URL structure is very important on the Web today. Your website and its content get shared in many different ways, from different places, on different devices. People find your URLs in search results, they click on your ads, they get to your blog from Facebook and they get information about your company emailed to them from a friend.

The device that your users share a link from will dictate the specific URL they share, and if that doesn’t match the device the link is viewed on, there’s a chance that the user receiving the shared link will see a confusing or misleading layout. We can fix this with redirects, but as we add more complexity and functionality into mobile websites, this becomes a serious task to manage. It’s often not done correctly.

We’ve all clicked on links from a search engine, an email or a tweet that take us to the wrong version of a website. For example, your friend wants to email you a Wikipedia article. They’re on a phone, so they email you the link en.m.wikipedia.org/wiki/Responsive_web_design, and you open that link on your laptop. You’ll see a single column of copy that spans the entire length of your 13 inch screen. This is annoying, but more importantly, it confuses and discourages visitors.

Wikipedia Mobile viewed on a laptop is a single column of copy that spans the entire length of the screen.
Wikipedia Mobile viewed on a laptop is a single column of copy that spans the entire length of the screen. Larger view.

SEO

Furthermore, www.mysite.com and m.mysite.com are different URLs. If redirects aren’t structured properly, search engines and analytics may not realize that two URLs serve the same content on different devices. Search relevance and analytics reporting can easily get splintered.

Even more detrimental is a URL structure that’s completely different for mobile. Instead of just adding the m. prefix to the URL, some mobile websites have a completely different page structure for mobile. This should absolutely be avoided, separate website or not!

Google, just one search engine, is taking measures to index and serve up the correct versions of websites, but we can’t rely on a computer to realize that two different URLs with the same content should be indexed, ranked and weighted as the same page. So to make sure Google indexes your different URLs properly (and fairly), you need to follow their guidelines and add extra code. Google shows you how in a tutorial, but at the top of the page, they make it clear that for SEO, responsive design is “Google’s recommended configuration.”

Google recommends responsive Web design for optimal search indexing.
Google recommends responsive Web design for optimal search indexing. Larger view.

Load Time

We need to keep the same page structure and the same URLs, but we should organize the display of the content based on the device. That presents a specific challenge for responsive design, though. Load time.

When using one code base to reorganize content, we inevitably create extra divs and other elements that get hidden. On mobile devices, over data networks and with limited processing power, this is an issue because whether they’re hidden or not, your phone loads all of the elements in your code.

Smart and efficient coding can minimize this load time. Sometimes people mistake responsive Web design for “time-saving” development, but in reality, coding responsive websites correctly is hard. Minimizing load time requires expertise in coding and a solid knowledge of how code and browsers work. But for the most part, a good developer can achieve speedy loading when it comes to text and other “light” content.

Images, however, are a much more serious challenge. Today, there isn’t a great answer.

Images

Images on responsive websites need to be large enough for a huge screen, even though they get sized down visually for small screens. So we create them large, but then our mobile websites suffer because we still have to load that full-size image. With bandwidth, cache size and processor limitations, this is not ideal.

There are plenty of responsive image solutions in the works for the future, like the picture element, and there are groups like the Responsive Images Community Group (RICG) who are looking for long-term, standards-based solutions. Still, there are no great solutions today to make sure that your images get served at an efficient file size or that they crop well when screen real estate is limited.

There are some workarounds, though. There’s Adaptive Images to swap images out at breakpoints. There’s jQuery Picture and Picturefill that simulate the functionality of the proposed picture element. For the proprietary platform my company builds on, we’ve created a jQuery plugin (released open source at Responsive Img) to efficiently handle switching images at different screen sizes. Although it solves load time issues, it still relies on JavaScript and isn’t a permanent, long-term solution.

At some point, there will be a solution. Today, 90% of the time, this issue is more of an annoyance than a complete roadblock. As data connections get faster and mobile phones get more powerful, it becomes even less of an issue. That, combined with the promise of future code standards for responsive images, means someday we won’t worry as much about load time issues with images, and we’ll have even less reason to do anything but responsive Web design.

I don’t want to downplay the load time issue, though. There are cases — certain websites that are too image-heavy or where complexity exaggerates the load time issue — where a separate website may still be smarter. Just like adding load time through responsive design, using a separate website is a compromise. It needs to be a calculated decision. Most responsive websites, especially with the help of JavaScript, can still squeak by with acceptable load times and reap all the additional benefits of responsive Web design.

Content Updates And New Features

What won’t change in the future is the increasing need for agile websites that improve and adapt based on user and Internet trends. We’re updating both content and functionality more and more frequently. With responsive design, we only need to add functionality to a single code base, saving time and creating focus. The amount of time it takes to maintain separate versions of the same website is often underestimated.

Furthermore, iteration is a growing key to successful modern websites. It’s becoming a necessity for websites today to get regular feature updates and add-ons, especially for e-commerce and Web apps. There’s so much data available on how people use your website that it’s an oversight not to adjust your user experience based on that data. At some point, maintaining and improving multiple versions of the same website means that time and money either go toward adding fewer features to both versions, or more features to only one (probably the desktop version). My company has a client that serves as a perfect example.

We’re retained to maintain and update a website we didn’t build, which has a completely separate mobile version. This large, corporate client has good analytics data, so they have lots of improvements and new initiatives for the website in the pipeline. Since we only have so many hours in our monthly retainer, and because the wish list of fixes and features exceeds those hours, we typically end up adding all the great new functionality to the desktop version only.

Right now, the mobile experience is far behind the desktop experience, and it doesn’t look like that will change anytime soon. There just aren’t enough hours. Yet, they’ve run campaigns based around QR codes and have promoted mobile use of their website at events.

In some ways, this is a huge oversight. In another way, it’s just an unavoidable problem caused by having a separate mobile website. For our client, it’s hard to argue that it’s smarter to release fewer new features for more website versions. They’d rather see initiatives go live then spend time and money maintaining the mobile version. With good reason, but with bad results.

This All Adds Up To One

To summarize, we know a few things. We know that all content and functionality needs to be available for mobile users. We know that today, URL structure is important. We know that load time is important, but it will one day be less of an issue. We know that websites need to always evolve, and that it takes time to implement changes and new features.

If you look at those factors in total, responsive Web design has to win out.

That said, coding technique and mobile strategy should still be considered individually for each project. There are times when images are too important, when functionality is required to be very different or when target user demographics prohibit responsive design. In my opinion this rarely happens, but it’s good to remember that responsive isn’t a blanket solution that fixes all of the Web’s issues.

One last thing. Don’t forget that for every separate mobile version you’re building and maintaining, a separate tablet version and TV version are right around the corner.

No matter how many versions you support, if you’re using separate websites, you’re supporting too many. Ideally, you should only have to support one. Responsive design makes sense today. It makes more sense tomorrow.

(cp)


© Andrew Thomas for Smashing Magazine, 2013.

Smashing Magazine

Opinion Column: Designing In The Transition To A Multi-Device World


  

When I think about where we are with the Web in comparison to other media in history, pinpointing it is really hard. Is it like when the Gutenberg Press was just invented and we’re experimenting with movable type, or are we still embellishing pages and slavishly copying books by hand?

Our knowledge of building digital things changes rapidly, taking us from newborn to adult and back again every couple of years. It’s both exciting and frustrating, because just when you think you have it all figured out, it completely changes. But if you’re like me, learning something new keeps things interesting.

So, it seems pretty normal that our methods of designing and building websites are questioned every so often. The argument to ditch design apps (or to drastically minimize the time spent in them) and go straight to the browser has popped up a lot in the past few years and then quite recently. It’s obvious that our digital world and, by proxy, our design process are in a state of transition. And they should be: considering design in the context of your materials and goals is always important.

I tend to shy away from prescriptive approaches. Most decisions are framed by our experience, and, as humans, we’re continually drawn to and seek out what we already believe (known as “confirmation bias”), ignoring the rest. So, I strive to keep that in mind whenever listening to advice about how things should be done. We’re all navigating the same changing landscape here. What many designers recommend is the right answer for them and not necessarily the right answer for you, or your client. As Cameron Moll more eloquently states:

“You know your circumstances, your users, and your personal preferences best. And if that means responsive web design — or design methodology or todo app or office chair or whatever — isn’t the right choice for you, don’t be ashamed if you find yourself wanting more, or at least wanting something else.”

That’s exactly how I feel right now. A lot of the explorations into Web design lately have been looking for the best ways to optimize an experience and to make it as flexible as possible across devices. These are important issues. But what about the design principles we’ve proven and iterated on through a variety of media? How can we apply what we’ve learned about design so that it can be utilized in an appropriate way to create websites in this multi-canvas world?

A New Medium With Old Roots

When we talk about designing a website today, we can’t help but mention the “What if?” challenges (or, if you’re a positive person, the opportunities) we face:

“What about embedded Web views?”

“What if the user has limited bandwidth?”

“What if JavaScript is turned off?”

“What about this awkward break point?”

It’s as if we have suddenly discovered the first medium in history that comes with limitations. We’re definitely not on an island here: Every medium has faced limitations — and continues to face them.

Typographic Design in the Digital Domain” with Erik Spiekermann and Elliot Jay Stocks

In an interview with Elliot Jay Stocks, legendary typographer and designer Erik Spiekermann explains how he finds it funny that designers today complain about limitations in designing for mobile:

“The way to design is the same [between print and Web]. You give content form, and the medium is always different anyway… I remember designing the little forms for medication, the little things that go inside, and I have the same issue… Essentially, I’ve got to cram a lot of complex content into a given format, however small that may be.”

He explains that when he designed for other media, the constraints were similar. You had to ask questions about the circumstances and about which information was the most important to the audience at that moment in time, and he asked things like, Are they really sick and trying to read this medical information? Are they at an airport and need to know their gate? Spiekermann goes on to say:

“So far, they [Web designers] have been bogged down by having to look at code all the time… So, now they can actually look at the problem. That’s why I said, in a few years time — however long it may take the individuals — they’ll design for the issue at hand and not for the medium.”

We’ve seen print and Web design converging — websites with beautiful typography that are easier to read. But with all of these little connected devices, we’re in an awkward transition phase, figuring out our design process. Some methods fit this new frontier really well, while others just don’t feel right to me. Like Spiekermann, the designer in me feels like we’re still getting hung up on the medium and the limitations and letting that dictate things, rather than designing for the issue at hand.

A List Apart
The new A List Apart is reminiscent of great print design.

For example, style tiles are a great new tool, but they are as the name indicates: styles. They can’t completely replace the layout because they do not indicate the content’s structure or balance or whether the navigation flow is right. Yet, I read about this kind of tool replacing the big-picture layout and design exploration all the time now.

Working on a design in small chunks feels like we’ve let the medium become the method. As a designer, you have to be able to see the forest and the trees. And the client needs to see what they are getting. We still need a holistic view of the canvas in order to solve design problems. It’s up to the designer to evaluate what form that should take.

In creating a more responsive Web, the process of how we design, implement and manage websites is evolving. We’re slowly convincing clients to go back to embracing the lifeblood of the Web, the content. We understand that rigid, unchanging canvases are not the way forward. However, embracing change doesn’t mean moving away from what works. The following quote from Stephanie Reiger about progressive enhancement speaks to how I feel about ignoring proven design principles in this transition:

“We have an opportunity to make the mobile web a million times more useful and relevant than the desktop web has been. The failure of the Obama site was not in the use of new techniques like responsive design, it was in forgetting that older principles and techniques still have an important role to play in building a better web. If anything, they are more important than ever before.”

The rules of design and usability that we’ve learned and iterated on over many, many years still exist here and can’t be discounted so easily. Designing responsively doesn’t change the fundamentals. The principles of negative (i.e. white) space and balance still matter. Gestural interfaces don’t make Fitts’ Law irrelevant. Design is still a set of decisions and about solving a problem.

Knowing When To Jump

Photoshop and Sublime Text are currently a few of the popular tools being used to design websites. They were not originally intended to be used to design websites or apps, especially considering the words “Photo” and “Text” in their names. They evolved into these roles.

When we talk about designing in a browser, we’re not really in a browser, designing. We’re in a code or text editor of some kind, and previewing the work in the browser. Although it’s possible (and some Web designers find it more comfortable), I don’t think we could purely and effectively “design” in a text editor. There would be a disconnect in the flow. Right now, it might be good enough for some aspects, but designing in the browser still limits us.

I realize that one of the main reasons for going into the browser is so that the client can see how the website will really look and function. But if we shift too quickly into markup and code, then how do we push for the next iteration of HTML, CSS and JavaScript? We need to envision it first. We need to ask the design questions that push things and see whether we can deliver part of it in the markup’s current standards — or else show the makers of standards and browsers one hell of a hack that inspires them to make it possible.

Inventing on Principle
Brett Victor shows us a more connected way to create with code.

Like anything, there’s a balance. Yes, the answer is, it depends. If you jump from sketching in your favorite bloated design app, then you’ll start thinking about layout and styling, rather than tasks, architecture and goals. If you jump from a design app to the browser (and text editor) too soon, you’ll start to get hung up on matters that have more to do with quality assurance and on fixing CSS issues at breakpoints.

Knowing when each stage of design peaks and loses value in the process is important and can be identified only through experience and by the type of project. The best design will happen when we get the jump points right. This could even mean working with a few tools at once, or going back to one tool before going forward again.

Responsive Task Planning
An example of responsive task planning, by Dennis Kardys, in Smashing Magazine’s Mobile Book.

Let me play a bit of the devil’s advocate. If we argue that the client isn’t getting a true representation of the product with a pixel-perfect comp (because they aren’t seeing it in the browser), then shouldn’t we design only in the browser or device most used by their audience? Shouldn’t we stop showing off what we’re doing in the latest Chrome or Safari browser and show the Web to the client through “normal” people’s eyes?

Showing the client what their users see by showing the website in a common browser or device could also improve the client’s perception. For example, if the client is desktop-focused, and you’ve seen that they get a good amount of tablet traffic, then show them what the website looks like on an iPad Mini. If they are using the latest and greatest devices and browsers but their users typically aren’t, then showing the design rendered in an older browser or phone would truly broaden their perspective.

Designing for the most ubiquitous browsers and devices is the most honest way I can imagine to represent the Web. In 2011, there were 6 billion phone activations, 80% of which were for feature phones. In case you aren’t following the news, the iPhone is not a feature phone. But we all know this scenario won’t happen. We live at the edge of the Web, and most Web designers and developers would rather imagine a Web with the latest browsers and smartphones — even if that’s far from the way most people experience it.

Progressive enhancement
Design to degrade gracefully. (Slide from “Progressive Enhancement and Mobile,” by Aaron Gustafson)

I get what folks like Brad Frost are saying when they talk about designers spending too much time doing the wrong thing. It’s a great point. Refining a layout too much in your favorite photo-editing app is like trying to accelerate a car in neutral. The refining stage should be done in the browser, when you’re designing the website. And — sorry to say, visual designers — that means knowing your material. Time to learn some markup and get your hands dirty!

I think we need to separate the way we explore our designs from how we present them to others. Just as showing experimental CSS in the latest browser isn’t being true to the design when showing it to a client, the same goes for showing a beautiful layout with a pixel-perfect “painting.” We have to be honest about what we show clients and stop making design promises that we can’t deliver on.

Watching Movies On Your Hand

Other industries are going through changes, too. Consider the film industry. It used to have it made: movie theaters set up with a huge screen and THX sound system, the audience sitting in comfortable chairs, in near total darkness. The entire experience was perfectly controlled.

The filmmaker knew that they only had to deliver a compelling story or a Brangelina butt shot to get people in the door. Now that has all changed. I can’t imagine how a movie director feels when they see someone watching their movie in a loud airport on a screen the size of their hand… Well, maybe I can:

David Lynch’s iPhone rant. (Some profanity, so use headphones.)

Some filmmakers are dragging their feet, claiming that this is cannibalizing their per-seat theater profits. However, some have decided to embrace this new ecosystem and give audiences the option to watch movies how they want. Actor and indie filmmaker Ed Burns is one of them, saying:

“You know, I think you have to be a realist in the way that, no musician wants anyone to listen to their music on an MP3 file going through a small set of tinny headphones. They’d much prefer that we all listen to it on a big sound system on an LP. But, you know, that’s over. And I think a similar thing has happened with the movie business.”

My lawyer gave me a great argument, because I was even resistant to it. He goes, if we go theatrical on this film, you’re going to open up in New York and L.A. Think about what happens if we go out on Video On Demand (VOD) and iTunes. You’re going to be in over 50 million living rooms. And the minute I heard that, I knew, OK, this needs to be embraced.

Great (Unknown) Expectations

The best part about designing for an unknown future is that it allows us to ask clients what is really important. It forces clients to look critically at their content. It forces them to look for ways to simplify how they present themselves to customers. Simplicity isn’t simple, but it’s the path we must take in refining our own design process in order to help clients shift their mindset. A convoluted process will continue to yield undesirable results.

Responsive Wireframing
Ed Merritt and Paul Boag give us a glimpse into how we might wireframe a responsive canvas.

We will still need to work in a mixture of static canvases for certain kinds of projects, especially complex Web applications. There is no way we could properly examine a problem if we can’t explore it first. If we visualize a solution only in small pieces, we’d be ignoring the big picture. If we jump too soon into markup or delay looking at it in the browser or on a device, we’d be missing something.

If anything, building for all of these different devices shows us that we need to work better with developers and clients. Without these relationships and mutual respect, it all falls apart. It can’t be dictated or dominated by any of these roles.

Artifact Conference
The Artifact Conference focuses on helping designers adapt to a multi-device world.

Learning who the client is and which artifacts they will understand best is key. I’ve learned that educating clients with things such as responsive patterns really helps them grasp the scope of the challenge here. As Dan Mall says, it’s about building an expectation and delivering on that:

“A responsive design process is like a scandal. You’ve gotta preemptively control the conversation. If your client wants to have conversations like this, it likely means you didn’t do a good job of setting expectations.”

Great communication up front has always been the way to make a project succeed. Now it’s more important than ever. The design process is shifting. For a designer, the best approach going forward is to find a way to put the problem first. Design from the content out, and find the best jump points to tools that fit the goal.

Until we get a real Web design application we’ll have to continue to determine these jump points as best we can. In the meantime, continue offering approaches and tools to the community, and embrace and improve on the ones presented to you. This will help us to continue designing a better Web.

(al)


© Francisco Inchauste for Smashing Magazine, 2013.

Smashing Magazine

Designing An Open-Source iPhone Game


  

I love games and I’m a huge math nerd, so I made a new iPhone game based on a famous math problem called The Seven Bridges of Königsberg. I’m selling it in the App Store, but I also want to share it with everyone, so I made it open source.

This article is the first in a series that will walk through iOS programming using this game as an example. This first article gives you an overview of the game and of iOS programming in general. We’ll look at a few specific pieces and see how the whole project fits together.

First Steps

This article uses the real game as the example. You’ll need a couple of things to start using the code:

  1. A Mac,
  2. The Xcode development environment from Apple, which you can get free from Apple.

After you’ve set up Xcode, go ahead and download the project from GitHub. Open it, and then run it by pressing the big “Run” button in the upper-left corner of Xcode.

Running Seven Bridges in Xcode

That will open the game in the simulator so that you can play for free and follow along with the article.

The Rules Of The Game

Seven Bridges is a puzzle game. The player visits a town of islands surrounded by rivers.

Hello Bridges level

The game’s interaction works with a single gesture: tap where you want the player to go. If you hit a bridge, you’ll cross it; if you hit a river, you’ll bounce off it.

Two Bridges level

The game lets you restart the level, undo your last move and go back to the menu. There are also a few other screens to support the game.

Level set selector

Levels selector

You won screen

Confused? Check out the Seven Bridge walkthrough video.

You’ll see similar layouts in popular games such as Cut the Rope and Where’s My Water?

Before We Start

Seven Bridges is a simple game. It doesn’t handle complex physics like Angry Birds does or rich textures like Infinity Blade does. Seven Bridges has just a single player who walks over bridges and bumps into rivers. It sounds easy, but a lot goes into even a simple game like this.

Seven Bridges is written in a combination of Objective-C and Objective-C++. If you’re used to programming in scripting languages such as JavaScript, then Objective-C will come as a shock.

Programming for iOS

Getting started with JavaScript is easy. You start with a little jQuery behind a button and go from there. Many iPhone programming tutorials make it sound like writing iPhone applications is just as easy. It’s not.

Objective-C has been around for nearly 30 years. Programming with it entails learning a large ecosystem and some fundamental concepts of how it all holds together. All of the Objective-C documentation assumes that you have a strong background in both object-oriented programming and the C programming language.

Objective-C is very different from JavaScript, and programming with it requires an understanding of some of the old-school programming fundamentals. Make sure you’ve read a book about object-oriented programming, such as Object-Oriented Analysis and Design with Applications by Grady Booch, as well as The C Programming Language by Brian Kernighan and Dennis Ritchie. Reading “The Objective-C Programming Language” guide from Apple is also a good idea.

The news isn’t all bad. Objective-C shows its age in some areas, but the tools are well written and the runtime environment is amazing.

The Files

You already have the code on your computer, so let’s get a better idea of what we’re looking at. You can tell what each file does by looking at its extension.

  • .h
    These files are class headers. Each of these files represents the public information available about a single class or object in the project.
  • .m
    These files are Objective-C implementation files.
  • .mm
    These files are Objective-C++ implementation files. Objective-C++ is a hybrid in which you can use parts of Objective-C and C++ in the same file. Seven Bridges uses Objective-C++ so that it can take advantage of frameworks written in C++.
  • .xib
    These files define visual views in the game where you can lay out buttons and other controls.
  • .png
    These files are individual images used in the game.
  • .pvr.gz
    These files contain large sets of images called sprite sheets. The images are combined into a single file so that they load faster and take up less space.
  • .plist
    These are XML properties files. They define the basics of how the application works and the positions of the images in each sprite sheet.
  • .m4a
    These are audio files that provide the sounds for the game.

Xcode projects also include a folder named your project.xcodeproj containing all of the project’s configuration files. Mine is named bridges2 because I messed up the project so badly that I had to start over.

The Frameworks

In addition to the standard Objective-C libraries, Seven Bridges uses three major frameworks.

UIKit

Every iOS application starts with UIKit. This comprehensive framework from Apple provides all of the basic controls your application uses, such as windows, buttons and text fields. Most of the classes in UIKit start with the prefix UI, like UIWindow and UIButton.

The easiest way to work with UIKit is by using the visual editor provided with Xcode. Xcode makes it easy to drag and drop controls into your application. It works well for business applications, but it wouldn’t know anything about the rivers or bridges in my game. For that, I need a gaming framework and a bit of code.

Cocos2d

You could draw on the screen directly with OpenGL, but that signs you up for a lot of work in managing each pixel on the screen. Game libraries provide higher-level support for placing images, creating animations and managing your game. There are a few for iOS.

I chose Cocos2d for iPhone because it’s well supported, has a simple API and comes with a lot of examples. It also has Ray Wenderlich’s excellent tutorials. Ray is a prolific writer about iOS games; every time I searched for a new topic, it led me back to him. His tutorial about collision detection provided the fundamentals for my game, and his simple iPhone game with a Cocos2D tutorial is a perfect little sample game.

Cocos2d handles all of the animations in my game, as well as the scenes where you’re actually playing; it also handles sprites, which we’ll get to a little later. It was originally written in Python for desktop applications, so make sure to search for “Cocos2d iPhone” when you’re looking for help on the Web. Cocos2d files start with the prefix CC.

Cocos2d handles user interactions, but it can’t handle interactions with objects. I need to know when the player runs into a river, bridge or any other object. That type of collision detection is made much easier with a physics library such as Box2d.

Box2d

Box2d is a physics engine written in portable C++. It can handle complex variables like gravity and friction, but we’re only using it for collision detection. Box2d files start with the prefix b2.

My game doesn’t use the complex physics of swinging candy from Cut the Rope or of sloshing liquids from Where’s My Water? It just handles a player walking around the screen and bumping into things. Box2d tells me when those bumps happen, and my code handles the rest.

Player bump interaction

In this article, we’ll see how to use these three frameworks together to build a scene, integrate sprites, respond to user gestures and detect collisions.

Building A Scene

The playable area of the game is drawn with LevelLayer, which extends the Cocos2d class CCLayerColor. This layer handles all of the drawing in the game and the responses when the user taps on the game screen.

The game is made up of a set of images called sprites. Each item in the game’s scene, such as a bridge or a piece of a river, is made up of a separate image file.

The 7 Bridges sprite sheet

Images used this way, instead of being created programmatically, perform much faster and can include subtleties such as shading and texture without needing a lot of code. The technique also makes delegating artwork easier because the artist doesn’t need to know anything about Objective-C.

The sprites all fit together into a single file called a sprite sheet. Cocos2d takes that image and a properties file containing coordinates and creates the individual images from it when the application runs.

The real reason to use a sprite sheet is performance. Ray Wenderlich has written a good article comparing sprite sheet performance to individual images. The short story is that sprite sheets are much faster than images loaded individually.

Managing sprite sheets manually is a real pain, so I used TexturePacker. It costs a little money, but $25 is well worth the hours of adjusting pixel coordinates it saved me. TexturePacker can also convert a sprite sheet to PVR (the internal image format for iOS) and compress it with Gzip so that it loads even faster.

Once we’ve created the sprite sheet, we’re ready to add the sprites to a scene.

Adding the Sprites

Xcode makes it easy to drag and drop images into a view, but that won’t work for dynamic scenes like our game levels. We’ll need to write some code.

Cocos2d interprets our sprite sheet with the CCSpriteBatchNode class. We initialize the sprite sheet once for the application and then use the individual items when we build our level.

CCSpriteBatchNode *spriteSheet = [[CCSpriteBatchNode batchNodeWithFile:@"bridgesprites.pvr.gz"
                                 capacity:150] retain];
[[CCSpriteFrameCache sharedSpriteFrameCache]
addSpriteFramesWithFile:@"bridgesprites.plist"];
[self addChild:_spriteSheet];

This code creates a new sprite sheet with our sprites file, initializes it with the properties file that defines the images in the sheet, and adds the sheet as a child to our current scene. You can see the full code for this in the init method of LevelLayer.mm.

Now that we have the sheet, we can use it to load individual sprites, like this:

CCSprite *bridge = [CCSprite spriteWithSpriteFrameName:[self @"bridge_v.png"]];
[spriteSheet addChild:bridge];
bridge.position = ccp(100, 100);

This code snippet creates a new sprite from the sprite sheet, adds that sprite as a child of the sheet, and positions it 100 points from the left side of the screen and 100 points up from the bottom. (We’ll get to what “points” are in the next section.)

Cocos2d manages the sprite sheets with a caching mechanism it calls the sprite frame cache. We loaded the frame cache in the previous code snippet when we loaded the bridgesprites.pvr.gz sprite sheet file and the bridgesprites.plist file that describes it. Cocos2d loaded all of those images into the cache, and we can now get them by name.

All positions in Cocos2d are based on a coordinate system in which point 0,0 is in the bottom-left corner. UIKit puts the point 0,0 at the top left of the screen. There are a few places where we need to convert back and forth further in the code.

Instead of using points directly, the game uses a tile system to position the sprites.

Pixels, Points and Tiles

iOS supports five devices:

  • iPhone 3.5 inch
  • iPhone 3.5 inch with Retina display
  • iPhone 4 inch with Retina display
  • iPad
  • iPad with Retina display

Different iOS device sizes

Supporting every device means handling multiple layouts. Cocos2d gives us a lot of help here by supporting points instead of pixels when specifying layout. Pixels represent an exact screen location, whereas points are relative to the device. This makes it easy to support Retina devices whose screens are the same size but pack in twice as many pixels.

Seven Bridges goes farther by defining a tile system. Tiles are a way of grouping pixels into larger squares for easier layout. We make the screen 28 tiles tall and at least 42 tiles wide. The tiles make it easy to define where the sprites go on each level. Switch the DEBUG_DRAW constant in Bridgecolors.h to true and you’ll be able to see the tile grid in the background of each level.

Two Bridges debug view

Touches and Interactions

UIKit handles touches on controls such as buttons and tables, but for the game scene we’ll need a generic touch handler. Cocos2d provides that with the ccTouchesEnded method. First, we have to tell Cocos2d that we want touch events, like this:

self.isTouchEnabled = YES;

Then, we implement the ccTouchesEnded method to get called whenever the user taps the screen.

-(void)ccTouchesEnded:(NSSet*) touches withEvent:(UIEvent*) event { 
   UITouch *touch = [touches anyObject];
   CGPoint location = [touch locationInView:[touch view]];
   location = [[CCDirector sharedDirector] convertToGL:location];

   // Do some stuff with the point that the user touched…
}

LevelLayer handles each screen touch with some simple logic:

  • If the player isn’t on the screen yet, then place the player sprite where the user has touched and return.
  • If the player is on the screen, then move the player from the current location to the place where the user has touched.

That’s all we need to do for the touch. The real logic of the game happens when we handle the collisions.

Boxes and Collisions

Each object on the screen is a sprite: a little image file that sits at particular coordinates on the screen. Cocos2d can handle the position and animation of those images, but it won’t know if they run into each other. This is where Box2d shines.

The LayerMgr class adds and removes all of the images from the layers in the game. When it adds an image, it also creates a box around it. Boxes are the fundamental concept of Box2d. They outline the position of an object on the screen and detect when it interacts with other objects. Box2d supports complex box shapes, but all of the boxes in this game are rectangles.

Whenever we add an image to the scene, we draw a box around it with Box2d. The box works with a helper class called a contact listener. This listener sits in a timer and asks the Box2d model if any of the objects have run into each other after each frame of the game.

The contact listener implements two important functions: BeginContact and EndContact. These functions are called when two objects come into contact and when that contact stops. When that happens, we save the data so that we can use it in the layer that renders the level.

void MyContactListener::BeginContact(b2Contact* contact) {
    MyContact myContact = { contact->GetFixtureA(), contact->GetFixtureB() };
    CCSprite *spriteA = (CCSprite *) contact->GetFixtureA()->GetBody()->GetUserData();
    CCSprite *spriteB = (CCSprite *) contact->GetFixtureB()->GetBody()->GetUserData();
    if (spriteA.tag == PLAYER || spriteB.tag == PLAYER) {
        _contacts.push_back(myContact);
    }
}

void MyContactListener::EndContact(b2Contact* contact) {
    MyContact myContact = { contact->GetFixtureA(), contact->GetFixtureB() };

    std::vector::iterator pos;
    pos = std::find(_contacts.begin(), _contacts.end(), myContact);
    if (pos != _contacts.end()) {
        _contacts.erase(pos);
    }
}

Once we’ve stored the data about the collisions, we use it every time we draw the level.

CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
    CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();

    if (spriteA.tag == RIVER && spriteB.tag == PLAYER) {
        [self bumpObject:spriteB:spriteA];
    } else if (spriteA.tag == BRIDGE && spriteB.tag == PLAYER) {
        [self crossBridge:spriteB:spriteA];

The contact listener gives us the two sprites that collided, and we’ll use the tag of each sprite to determine how to handle it. When two sprites run into each other, we react with some simple logic:

  • If the player contacts a river, then bounce back.
  • If the player contacts a bridge, then check whether the bridge has been crossed.
    • If the bridge is crossed, then bounce back.
    • If the bridge isn’t crossed, then cross it and move the player to the other side.

Separating the player’s movement from the collision makes it easy to move the player around the screen. We don’t have to define islands or worry about managing where the player is allowed to move. We just place each sprite in the level and wait for the player to run into it.

Defining Levels

Each level in the game is defined in a separate JSON document. Separating the level definitions from the code is important so that we can update the levels or add new ones without having to change the code.

Each level defines a name, an ID and a set of objects that go in the level.

{
    "level": {
        "name": "Hello Bridges!",
        "rivers": [
            {
                "x": "14",
                "y": "b-t",
                "orient": "v"
            }
        ],
        "bridges": [
            {
                "x": "14",
                "y": "m",
                "orient": "h"
            }
        ]
    }
}

Each object has a coordinate in the tile system and a set of properties that define how the object works. For example, a bridge specifies an orient property to determine whether the bridge is horizontal or vertical and a color property to determine whether the bridge has a particular color. A separate page defines everything you can put in a level.

Many games define levels in XML, but I chose JSON because it’s faster to parse and works better with the Web. One day, I’d like to create a mode in which you can load new levels from a website without having to download a new version of the game.

The Level class defines each level; levels are controlled by a LevelMgr. The level manager loads the levels, sorts them for the menu and creates the thumbnails of each level on the menu screen.

Seven Bridges does a lot more, but this is a good place to stop for the first article.

What’s Next

This article has walked us through some of the core parts of games for iOS, but there’s a lot more. You can get Seven Bridges (not free) or download the source code and run it for free in the simulator.

We’ve reviewed the major frameworks, looked at the anatomy of a game, and learned the basics of user interactions. In the next article, we’ll delve deeper into the pieces and see how they all fit together.

(al)


© Zack Grossbart for Smashing Magazine, 2013.

Smashing Magazine

A Critical Approach To Typefaces


  

I’ve always wondered, “What is it that makes a typeface or any other design good?” However simplistic this question may seem to typographers, it is a legitimate question many of us are trying to answer.

After several years working as a professional type designer, teaching, and running a type foundry, I pretty much gave up my attempts to find a golden set of rules. The answer is not so simple. There is no established set of features which, when present, make a typeface good (and I do not mean just “looks good,” but also works good). But there is a body of knowledge that can provide the necessary answers and also inform your inevitable personal view.

Author’s friend scared by his own library

I will try to give you a condensed recipe on how to approach typefaces critically and perhaps even ruthlessly. In my humble opinion, this is the best way to get oriented in the field. Indeed, looking at typefaces this way is more generic and painful, and it does take longer, but it is a transferable skill and is totally worth it. Much better than any specific answer you can get.

In this article we will cover two steps:

  1. Select your sources carefully,
  2. Study materials from these sources closely and critically (“to study” means both to look and to read).

I tend to refer mainly to critical reading. Many young designers despise reading. Believe me, I hate those boring historical and theoretical treatises as much as you do, but even though images are worth a thousand words, they alone cannot say everything.

1. Selecting Sources

There are a lot of designed and written materials available. Unfortunately, it’s not always clear which ones are appropriate and trustworthy. So how do you find out?

Always try to be aware of the nature of the source. Are the materials educational or promotional? The difference might not always be clear. Promotional texts boast about all the positives and obscure any negatives. They are written for the benefit of the author or producer. Educational resources generally attempt a more balanced view and they are written for the benefit of the reader.

How can you find out whether the source is experienced or just well-known? Does not the first imply the second usually? Not always. Unlike celebrities who are primarily good at self-promotion and not necessarily at the job they do, authorities are those who actually have sound experience or knowledge, yet they might not be well-known. You would do better listening to the latter. It is hard, but try to disregard the PR noise and look at what they have done, if the quality of their work is consistent and respected and if they are conscious of what they are doing (e.g. they have a methodology). Note that length of the experience is a good signal, but not necessarily a solid proof of quality. There are old designers doing terrible work and young ones doing great too.

Keep some perspective: diversify your sources (never listen to just one), listen to what their competitors say about them and make sure you know the community they belong to — people tend not to criticize their own (at least not publicly).

The author’s friend in his reading room

People have different characters and different politics. Be aware of that when selecting sources. I would not completely trust anyone who has never publicly admitted a mistake. For such a person, perfect public image is more important than the validity of the discourse.

You certainly do not have to read everything. For some, it is better to stick with a few examples and study them deeply; others prefer a broader perspective with less depth. But read you must.

2. Critical Study

Here is the painful bit. You have gathered materials to read and look at, and now you must study and question what you’re reading. Here are a few simple tests to start with:

Informed Experience

Are the authors’ actual experiences relevant to what they are talking about? Example: if a brilliant designer is explaining politics in South Korea, should you listen? Even if the designer has been to South Korea, does it constitute an informed experience? Perhaps not.

Context

Is the statement generally valid or is there a context to it? A great example is the discussion about the use of small caps where Joe Clark disputes their utility in academic writings. One of the common rules in Anglo-Saxon typography is to typeset abbreviations in small caps to make them less pronounced. According to Clark, this actually hinders the reading and skimming of academic texts. Change the context and the validity of the whole statement changes. The article is amusingly rude and critical, but remember to read the reactions, too.

Blindfolded colleagues experiencing relativism

Evidence Quality

Is the statement supported by any evidence? Is the evidence relevant to the point being made, and does it illustrate the problem? Example: type designers will often mention how much time they spent developing their new type family, but is it really that important to know? Does a longer (or shorter) production time make their type family any better or worse? This information does make you think about the value and effort put into the project, but it is not actual evidence of quality.

Evidence Completeness

Does the evidence cover the broad picture or is it just a narrow snapshot? Are the conclusions made with a broad or narrow perspective? Example: if I were to design a generic book typeface and conduct preliminary research, should I analyze book typefaces from just five books from a few different countries? Is that a representative sample? Perhaps not.

Reality Check

If someone writes about originality or critical discourse, does it mean that person is actually original or critical? Articles are often written to denote the discussed quality in the author. Example: feel free to apply right now.

Testability

Does the typeface have features that are testable? Run the tests and see for yourself. Example: check a cross-platform web font in browsers your visitors use. Does it provide a consistent reading experience across a wide array of browsers, or is the appearance highly inconsistent or even erratic? If it’s the latter, then perhaps the web font is not so cross-platform.

Motives Check

What are the author’s motives? If an author appears biased, check their reasoning twice. Motives are good, but supported claims are better. Example: look at someone commenting on their competitor’s work. Naturally, disagreement is in their job description, but do they have valid basis for what they say? No? Then ignore their comments! You do not want to be used for someone’s propaganda against their competitors.

The author’s friend again bewildered by the wider context

Post-Modern Check

Do not give up your aspirations for objective knowledge too soon. Not everything is a matter of personal taste. Isn’t it better to have a slightly imperfect or incomplete objective statement, rather than a bunch of subjective feelings (depending on the subject of discussion)? Example: six pixel type is not readable, but that’s hardly a matter of personal taste. If someone says so, then maybe they do not have any opinion at all. (It is nearly impossible to fit readable Latin lowercase within six pixels.)

And Then…

Read, see and listen. Discuss. Think. Repeat. (Preferably in that order.)

Optionally, you might also share and test what you have learned and write something. It is good for everyone in the field (especially for those who are criticized; talk to them, but stay civil) to keep the critical discourse rolling, and it helps to strengthen your reasoning. There are plenty of opportunities on social networks (btw. Twitter has a pretty lively community of type designers) and blogs. Talking to your friends and colleagues works pretty well, too.

Playing with these and other questions ignites the curiosity which is necessary for close inspection of other people’s designs. Why else would you look at it for so long?

There is a very simple rule: the more questions you ask, the more insights you will get. And to ensure the answers are useful, you need to remain critical. Once you gather enough you will know how to recognize a good typeface.

Further Reading

So far I carefully avoided being specific in this article, but I must admit that providing actual starting points seems worth betraying any sort of attempt for objectivity. In the following list I tried to avoid the most known books and show what enthusiastic typographers would read and what I also deem easy to digest. Please, do consider this selection biased and limited:

Inside Paragraphs: Typographic Fundamentals written by Cyrus Highsmith.
This new and short book is an introduction to the merits of type spacing for design students. It expands on a chapter on spacing hierarchy from Gerrit Noordzij’s book LetterLetter. What I recommend about it most is the nice common-sense analytic style.

Counterpunch: making type in the sixteenth century; designing typefaces now written by Fred Smeijers.
Long-awaited second edition was finally published last year. While it may seem very historical at first, this book is worth re-reading every three years as it explains, not just presents. It is a fine example of research and reasoning in typography.

Letters of credit: a view of type design written by Walter Tracy.
There are two parts of this book. One is on printing and typefounding and illustrates how technology defines type design. The other is a set of in-depth typeface reviews. Reviews by an experienced type person, that is.

While You’re Reading written by Gerard Unger.
Very enjoyable read, a summary of Unger’s thoughts on what I would call “human-centered type design”.

MA Typeface Design at the University of Reading
The website does not contain only the type specimens, but in many cases there are also essays about the development (look under the mysterious abbreviation ‘RoP’ which stands for ‘Reflection on practise’) some of which are very worth reading. If you like some typeface, you might as well read the essay too.

Illustrations created and designed by Anna Giedryś.

(cp) (il)


© David Březina for Smashing Magazine, 2013.

Smashing Magazine

Part 1: Application: A Thorough Introduction To Backbone.Marionette, Part 1: Application


  

Backbone.js is quickly becoming the most popular framework for building modular client-side JavaScript applications. This is largely due to its low barrier to entry; getting started with it is super-simple. However, unlike Ember.js, Backbone, being so minimal, also leaves a lot up to the developer to figure out.

So, once you start getting into more advanced applications, it’s no longer so simple. Backbone.Marionette was created to alleviate a lot of the growing pains of Backbone development. Backbone.Marionette “make[s] your Backbone.js apps dance with a composite application architecture!,” according to its author.

This “composite” architecture refers mainly to the numerous view types that have been provided to help with subview management. We won’t be discussing those views today (although we will touch on regions, which are a small part of the subview management that Marionette offers), but you can find documentation for this project in the GitHub repository. It offers numerous components that extend Backbone and that enable you to write less boilerplate and do more stuff with little to no hassle, especially when it comes to views.

The Central Application Object

Most of the time, when someone creates a Backbone application, they make a central object that everything is attached to, which is often referenced as App or Application. Backbone doesn’t offer anything to make this object from, so most people just create a main router and make that the app object. While it’s great that people are attaching things to a central object so that the global namespace isn’t so convoluted, the router was not designed to handle this task.

Derick Bailey, the creator of Marionette, had a better idea. He created a “class” that you could instantiate an object from that is specifically designed to handle the responsibilities of being the go-to root object of the entire application. You create a new application with var App = new Backbone.Marionette.Application(), and then, when everything is set, you start the application with App.start(options). I’ll discuss the options argument soon. For now, just remember that it’s optional.

Initializers

One of the coolest things about Marionette’s Application is the initializers. When your code is modular, several pieces will need to be initialized when the application starts. Rather than filling a main.js file with a load of code to initialize all of these objects, you can just set the modules up for initialization within the code for the module. You do this using addInitializer. For example:

var SomeModule = function(o){
	// Constructor for SomeModule
};

App.addInitializer(function(options) {
	App.someModule = new SomeModule(options);
});

All of the initializers added this way will be run when App.start is called. Notice the options argument being passed into the initializer. This is the very same object that is passed in when you call App.start(options). This is great for allowing a configuration to be passed in so that every module can use it.

A few events are also fired when running through these initializers:

  • initialize:before
    Fires just before the initializers are run.
  • initialize:after
    Fires just after the initializers have all finished.
  • start
    Fires after initialize:after.

You can listen for these events and exert even more control. Listen for these events like this:

App.on('initialize:before', function(options) {
	options.anotherThing = true; // Add more data to your options
});
App.on('initialize:after', function(options) {
	console.log('Initialization Finished');
});
App.on('start', function(options) {
	Backbone.history.start(); // Great time to do this
});

Pretty simple, and it gives you a ton of flexibility in how you start up your applications.

Event Aggregator

The Application object brings even more possibilities for decoupling a Backbone application through the use of an event aggregator. A while back I wrote a post about scalable JavaScript applications, in which I mentioned that modules of a system should be completely ignorant of one another, and that the only way they should be able to communicate with each other is through application-wide events. This way, every module that cares can listen for the changes and events they need to so that they can react to them without anything else in the system even realizing it exists.

Marionette makes this kind of decoupling largely possible via the event aggregator that is automatically attached to the application object. While this is only one of the mechanisms that I wrote about in that article, it is a start and can be very useful in even smaller applications.

The event aggregator is available through a property in the application called vent. You can subscribe and unsubscribe to events simply via the on and off methods, respectively (or bind and unbind, if you prefer). These functions might sound familiar, and that’s because the event aggregator is simply an extension of Backbone’s Event object. Really, the only thing new here that you need to worry about is that we’re using the events on an object that should be accessible everywhere within your app, so that every piece of your application can communicate through it. The event aggregator is available as its own module too, so you can add it to any object you want, just like Backbone’s Event.

Regions

Region is another module for Marionette that enables you to easily attach views to different regions of an HTML document. I won’t go into detail about how regions work here — that’s a topic for another day — but I’ll cover it briefly and explain how to use them with Application.

A region is an object — usually created with new Backbone.Marionette.Region({ el: 'selector'}) — that manages an area where you attach a view. You would add a view and automatically render it by using show. You can then close out that view (meaning it will remove it from the DOM and, if you’re using one of the Marionette views, undo any bindings made by the view) and render a different view simply by calling show again, or you can just close the view by calling close. Regions can do more than that, but the fact that they handle the rendering and closing for you with a single function call makes them extremely useful. Here’s a code sample for those who speak in code rather than English:

// Create a region. It will control what's in the #container element.
var region = new Backbone.Marionette.Region({
	el: "#container"
});

// Add a view to the region. It will automatically render immediately.
region.show(new MyView());

// Close out the view that's currently there and render a different view.
region.show(new MyOtherView());

// Close out the view and display nothing in #container.
region.close();

If you want a Region directly on your application object (e.g. App.someRegion), there’s a simple way to add one quickly: addRegions. There are three ways to use addRegions. In every case, you would pass in an object whose property names will be added to the application as regions, but the value of each of these may be different depending on which way you wish to accomplish this.

Selector

Simply supply a selector, and a standard region will be created that uses that selector as its el property.

App.addRegions({
	container: "#container",
	footer:    "#footer"
});

// This is equivalent to
App.container = new Backbone.Marionette.Region({el:"#container"});
App.footer    = new Backbone.Marionette.Region({el:"#footer"});

Custom Region Type

You can extend Region to create your own types of regions. If you want to use your own type of region, you can use the syntax below. Note that, with this syntax, el must already be defined within your region type.

var ContainerRegion = Backbone.Marionette.Region.extend({
	el: "#container", // Must be defined for this syntax
	// Whatever other custom stuff you want
});

var FooterRegion = Backbone.Marionette.Region.extend({
	el: "#footer", // Must be defined for this syntax
	// Whatever other custom stuff you want
});

// Use these new Region types on App.
App.addRegions({
	container: ContainerRegion,
	footer:    FooterRegion
});

// This is equivalent to:
App.container = new ContainerRegion();
App.footer    = new FooterRegion();

Custom Region Type with Selector

If you don’t define el — or you want to override it — in your custom region type, then you can use this syntax:

var ContainerRegion = Backbone.Marionette.Region.extend({});

var FooterRegion = Backbone.Marionette.Region.extend({});

// Use these new Region types on App.
App.addRegions({
	container: {
		regionType: ContainerRegion,
		selector:   "#container"
	},
	footer: {
		regionType: FooterRegion,
		selector:   "#footer"
	}
});

// This is equivalent to:
App.container = new ContainerRegion({el:"#container"});
App.footer    = new FooterRegion({el:"#footer"});

As you can see, adding application-wide regions is dead simple (especially if you’re using the normal Region type), and they add a lot of useful functionality.

Conclusion

As you can already see, Marionette adds a ton of great features to make Backbone development simpler, and we’ve covered only one of many modules that it provides (plus, we’ve touched on a couple of other modules that Application itself uses, but there’s plenty more to learn about those). I hope this will entice Backbone programmers a bit and make you eager to read the rest of this series, when I’ll cover more of the modules.

Credits of image on start page: Dmitry Baranovskiy.

(al)


© Joseph Zimmerman for Smashing Magazine, 2013.

Smashing Magazine