Archive for September, 2012

Testing Websites in Game Console Browsers

Testing Websites in Game Console Browsers

More than one in eight internet users in the UK, US, and France—and nearly one in four American teens—uses a game console to get online, according to studies from 2010 and 2011.1

This isn’t new. Internet capabilities were introduced in consoles back in 1997 with the Game.com, which allowed users to upload scores by plugging in a dial-up modem and even to check email and browse websites if they had an internet cartridge.

Today’s three main consoles (Microsoft’s Xbox 360, Sony’s PlayStation 3, and Nintendo’s Wii) all have internet capabilities. The Xbox 360 is the only one of these without an official browser, but Microsoft has announced it will release IE9 for the console shortly. Some companies have gone so far as to design experiences specifically for consoles, such as Google’s 2007 version of Reader for the Wii, which is now intended for any TV console.

Add in a vast array of handheld consoles with browsers—like Sony’s PSPs and Nintendo’s DS line—and we have 15 years of internet-enabled gaming devices of all sizes and shapes. Yet to date, we’ve talked about game console browsers very little.

It’s time we change this.

Today’s consoles may offer subpar experiences with little browser choice, but that doesn’t mean we can ignore them. After all, “We can’t predict future behavior from a current experience that sucks,” as Jason Grigsby says.

As more console makers offer internet-capable devices—and as smart TVs continue to enter the market—now is the time to plan how our sites will adapt to these new contexts. And that means getting comfortable with today’s game console landscape.

Who uses a game console’s browser?

TV game consoles aren’t just for gamers. Now they’re marketed and sold for their content-delivery features, such as Blu-ray and access to Netflix. Some consoles also have apps for Twitter, Facebook, Skype, and Foursquare, so there’s every chance a user may be visiting your site through one of these.

According to Pew Internet, 80 percent of American teens age twelve to seventeen own a game console and half own a portable gaming device. Handheld consoles are most popular amongst young teens, with two-thirds of twelve- and thirteen-year-olds owning one.

Among adults, Pew found that overall, men are slightly more likely to own a game console, but women are slightly more likely to own a portable console.

In the UK, young adults ages sixteen to twenty-four are most likely to own a game console, and 20 percent of them visit websites using theirs. Amongst children ages five to fifteen, 5 percent access the internet with a game console more often than with any other device. In fact, this age group is more likely to access the internet with a console than with a mobile phone or tablet.2

Amongst all age groups, game consoles are more popular than tablets as internet-browsing devices, possibly because people are more likely to own a console.

In short, all kinds of people are using game console browsers, for all kinds of reasons. In households that own a PC, a console may be a convenient extra way to browse the internet if there’s competition for the more conventional device. Handheld consoles are also popular with parents who don’t want to give their child an expensive smartphone. Amongst primary-school children, the Nintendo DS is particularly popular; in some schools, it’s even used in lessons.

We’ve made mistakes in the past by assuming which tasks mobile users would want to complete. But just like the thousands of eBay customers buying cars using mobile phones each week, some console browser users are already doing things we may consider “advanced”—like signing up for a bank on the PS3, as twenty people tried to with Kiwibank last year.

Console browser testing

While you may not be able to test your sites on every console out there, it’s helpful to acknowledge their existence and understand their quirks so you can build a good experience for as many people as possible. To do that, consider all three of the major console types:

  1. Consoles that plug into a TV screen, such as the Nintendo Wii, Sony PS3, and Microsoft Xbox 360.
  2. Handheld consoles such as Sony’s PSP and Nintendo’s DS.
  3. Phone consoles, designed primarily as phones but with console buttons (as opposed to consoles with phone capabilities).

As community testing sites pop up around the world, it makes sense to get some of each of these types of consoles into them—particularly those with the most diverse features.

For a TV console testing device, Nintendo’s Wii has a motion controller that’s useful to test navigating a site with. There’s also the new Wii U coming out, which will have a touchscreen on the controller that links to the TV. Sony’s PS3 is useful for testing ease of navigation with a conventional game controller, while the Xbox 360 will be an important device to try when IE9 is released for it.

The two most popular series of handheld consoles are the Nintendo DS and the Sony PSP. The most recent handheld console from Sony is the PS Vita, which has an optional 3G model and can also be used as a controller for the PS3. The older internet-enabled handheld Sony models are the PSP-1000, PSP-2000, PSP-3000, and PSP Go (the PSP-E1000 leaves off internet capabilities).

For the DS line, the DSi and 3DS are useful because they have different browsers. The older DS and DS Lite require a physical browser cartridge rather than having a browser preinstalled or available via download, so it’s likely that fewer people browse the internet on these.

Testing on TV consoles

A large TV screen doesn’t mean better definition. Text can be pixelated and difficult to read, especially when a browser scales content up. Even though TV screens are generally bigger than desktop computer screens, viewers sit further away from them, so they may actually seem smaller.

Sony’s PlayStation 3

The Sony Playstation 3

The PS3 has a WebKit-based NetFront browser. The browser width is restricted, so it’s a lot narrower than the width of the TV.

The thumbsticks move the cursor and scroll the page. L1 (on the upper left) is a back button; R1 (on the upper right) is forward. Pressing the triangle brings up a menu for actions like search and bookmark, and the D-pad moves the cursor to focus between links on the page.

Multiple windows can be opened and accessed using L3 (pushing in the left thumbstick) and cycled through using L2 and R2 (the lower left and right buttons).

Browser support

Nintendo Wii

The Nintendo Wii

The Wii has an 800px-wide Opera 9 browser (the height varies depending on the screen). The remote, used like a laser pointer, vibrates on hovering over a link. Moving the cursor to the edge of the screen and pressing the trigger scrolls the page. The + and - buttons zoom in and out. Pressing 1 on the remote goes to favorites; 2 shows a version of the page without layout styles.

The remote feels heavy after typing for a while or trying to pick through links on a page, so navigating can be fiddly unless links are big. This becomes problematic on sites with clickable areas that are small and close together.

Often, a site would start loading, crash, and immediately go back to the console’s home screen without any warning or error.

  • HTML5 support: Failed to run
  • CSS3 test: Failed to run

Testing on handheld consoles

Like modern TVs, handheld consoles have wide screens, rather than tall ones like a mobile phone in portrait mode. This means many responsive websites show a big-screen version of a site, even though a small-screen design might be more appropriate.

Sony PS Vita

The Sony Playstation Vita

The newest of the PS line, the Vita is the first to include a 3G option. It has a touchpad on the back used in some games to keep thumbs out of the way during play, but the browser doesn’t take advantage of it.

The Vita’s browser is a WebKit-based version of NetFront. Strangely, it identifies itself as Silk in its user agent string, which is the browser for Amazon’s Kindle Fire.

Sites can only be viewed in landscape at 960x544 at 220ppi, so most show a display optimized for wide screen, rather than a small-screen view. Up to eight windows can be open at once.

While the Vita is a Sony product, its experience is nothing like the PS3—the browser relies heavily on the touchscreen and doesn’t seem to take advantage of the game controls on the device.

Browser support

  • HTML5 test: 58/500
  • CSS3 test: 32%

Nintendo DSi

The Nintendo DSi

The DS line is distinctive for its two screens and stylus. The bottom screen is a resistive touchscreen, like the screen on the back of an airplane seat, rather than capacitative, like a smartphone. The DSi screens have relatively small dimensions (256x192) and low ppi.

The DS will take advantage of both screens to display a site optimized for small screens, treating them as a single tall column. On non-optimized sites, the site is mirrored on the two screens: one zoomed in, one zoomed out. There is no multi-touch, so no pinch-to-zoom, making long lines of text difficult to read. There are no font styles like bold or italic either, and text size is limited to a range.3

Browser support

  • HTML5 test: 89/500
  • CSS3 test: Failed to run

Nintendo 3DSXL

The Nintendo 3DSXL

This device has a stylus and three cameras: two on the back for 3D pictures and video and one on the front. Special glasses aren’t needed to view things in 3D, but the device does have to be held at just the right angle and distance. The depth of the effect can be adjusted using a physical slider.

Only the top screen is 3D, and it’s wider than the bottom one, which is a 2D resistive touchscreen. The screens are physically bigger than the smaller 3DS model, but the pixel dimensions are the same (800x240 on the top; 320x240 on the bottom), so text is blocky. When a page scrolls into the top screen, gaps appear on either side because of the difference in the two screen sizes.

The older DS models offer an Opera browser, but newer ones have a NetFront browser installed by default, accessible from the home screen.

Sites are shown in 2D, but images using the MPO format can be viewed in 3D in the top screen. MPO images are a combination of two JPEG files, so the fallback is a single JPEG. The catch is, embedded MPO images can’t currently be viewed in 3D inline using the browser installed on the device; they have to be downloaded and opened as a file.

The D-pad is used to cycle through links; a line is drawn around elements that are selected. The thumbstick is used to scroll.

There are zoom icons on the touchscreen, and the X and Y buttons also zoom in and out. The shoulder buttons go forward and back through the browser history.

On zooming in, automatic text-wrap forces line lengths to adapt to the width of the viewport. The browser can be used while a game is suspended in the background, which allows gamers to look up tutorials or walkthroughs while playing. I’ve noticed this feature appearing on other consoles as well.

In tests, some sites stopped loading because they were too big and the system ran out of memory, which was also a common problem on the DSi.

Browser support

  • HTML5 test: 98/500
  • CSS3 test: 42%

Testing on console phones

Manufacturers have been attempting to combine handheld consoles with phones since 2003’s Nokia N-Gage. Today, the most interesting of these is the Sony Ericsson Xperia Play, which looks like a phone, but has slide-out PlayStation-style controls.

The Sony Ericsson Xperia

The screen is much higher quality than the PS Vita. It runs Android 2.3 (Gingerbread). Anytime the game controller drawer is open, screen orientation is set to landscape. Overall, sites look good and the browser is just as capable as that of any other modern smartphone.

Even though it’s closer to a phone than a game console, it’s important to consider this hybrid device. As smartphones compete with handheld consoles, we may well see more like it.

Browser support

  • HTML5 test: 212/500
  • CSS3 test: 42%

On the horizon

A whole host of devices are on their way that will present new challenges for designers and developers. Internet browsing on consoles is set to increase as console makers release devices with better browsers and more capabilities—features such as NFC for micropayments in the upcoming Wii U, and voice control and Kinect gesture support in the Xbox 360’s coming IE9 browser. There have already been some interesting experiments with gestural interfaces in browsers using a Kinect and DepthJS.

Second screen

All three major TV consoles have or are moving toward a second screen. The PlayStation 3 can already connect with a handheld PS Vita and allow the user to play games on the device directly from the PS3 console (Vita Remote Play). It can also be used as a second controller.

Nintendo is coming out with a similar offering, the Wii U: an updated console and handheld gamepad with a touchscreen that can be used as a keyboard. Users can share with the TV what they’re browsing on the gamepad by swiping the content toward the TV.

Meanwhile, Microsoft has announced SmartGlass, which will enable users to connect a smartphone with their Xbox and use it as a second screen. Rather than connecting with a bespoke device, the console interacts with any phone or tablet.

With SmartGlass and a Kinect, it may even be possible to “pull” content from one screen to another, as demonstrated in Aral Balkan’s hack.

New devices

New players are also bringing interesting devices to the market. One of these is the Razer Switchblade. It’s part Windows computer, part handheld console. The images on the keyboard’s keys change depending on what content is being viewed. With a form factor similar to a netbook, it has a four-inch trackpad within the keyboard area that can also be turned into a miniature second screen. It’s rumored to be using a version of IE7 with a low score of 40 in the HTML5 test.

The Ouya, a TV game console announced and funded on Kickstarter, is due to be released in March 2013. It will feature a conventional controller, and the console will run on Android. It’s not yet known which browser it will have, but it will have web capabilities.

Designing with consoles in mind

Console browsers live in an uncomfortable area between mobile and tablet, desktop and TV. They often act like mobile and desktop browsers, but the way we interact with them is so different.

Jason Grigsby talks about this challenge in his presentation on The Immobile Web: HDTVs and iMacs have the same pixel dimensions, but a desktop is viewed from a few inches away; a TV, from a few feet. On a TV, a linearized design that’s common for small screens may actually be more appropriate than a design for a wide screen. The difference isn’t screen width, but viewing distance. In fact, Google’s TV design patterns even suggest you simulate this experience by using a mobile phone as your “model” when designing.

It’s also very difficult to detect whether a site is being viewed on a TV. User agent strings aren’t a reliable or future-friendly detection method, since many imitate other browsers’ strings. Media types are also often ignored, as Patrick Lauke has noted.

Throw into this mix the possibility of a user viewing a site on TV while interacting with it on a second-screen device, and things get a whole lot more complicated.

What we can do now

We’re designing for mice and keyboards, for T9 keypads, for handheld game controllers, for touch interfaces. In short, we’re faced with a greater number of devices, input modes, and browsers than ever before.

Ethan Marcotte, Responsive Web Design

We can’t tailor experiences for every possible use case on every device, but we can use what we know about console web browsing to build a better overall experience. Like we’ve done by designing with mobile in mind, considering how a site could be used on a console can have a knock-on effect of making it easier to use overall.

Use progressive enhancement so people can access your site’s content even on a device that doesn’t support certain features. Optimize so it downloads fast. Insert media query breakpoints where it’s appropriate for the content, rather than based on widths of common devices. Consider how someone will fill out a form on a console, and look into adding speech recognition to fields.

It’s tempting to focus on retina screen experiences, but we also need to consider how a site will look at the other end of the scale. People don’t replace their TVs as often as other devices, so make sure a design still works well on poorly configured, pixelated, low-contrast screens. Plus, as Cennydd Bowles has noted, while pixel densities increase in some places, they’ll decrease in others as cheap screens appear on more and more devices.

We’ve been here before. As Future Friendly taught us, the challenge of designing for yet more contexts may be daunting, but it’s inevitable. If we care about making our sites accessible to everyone, then we have to start looking beyond desktop and mobile. It’s time we take game console browsers seriously.

Footnotes

[1] According to a 2011 Ofcom report (PDF) and a 2010 Pew Internet study. Ofcom is the UK’s independent regulator for the communications industry and runs both international and UK-specific surveys on the communications market. The Pew Research Center is a nonprofit “fact tank” that provides information on American issues, attitudes, and trends.

[2] UK stats are again from 2011 Ofcom reports: one on devices used to visit internet websites by age, and another on UK children’s media literacy (PDF).

[3] You can read an in-depth writeup of the DSi’s browser on my personal blog.

Translations:
Italian
Portuguese


RSS readers: Don't forget to join the discussion!


Typography rules: Eye-Catching Headlines with slabText for jQuery


  

Typography in web design has long been treated as an orphan. With the rise of web fonts the situation changed and thanks to jQuery we have loads of elegant little helpers to make our sites prettier. The more advanced plugins even introduce possibilities formerly only known to print designers. Today we are going to take a look at slabText.js. This tool will split longer headings into two or more rows and set these rows to full justification, where each row is scaled individually, which guarantees for an eye-catcher.

slabText: FitText clone at first, but not at second sight…

You might have already put your hands on FitText, a very popular plugin, that at first sight seems to achieve the same tasks slabText intends to. The difference is small, but profound. FitText only scales one-row headings to the size of its container.

slabText takes the next step and provides almost the same functionality for longer headings. Taking a longer title marked H1, slabText will split it in rows. Then it takes these rows and justifies them to the left and to the right, which obviously requires changes in font-size, as not all words are created equal. In doing so, slabText calculates by itself where to fill in the line breaks. Thinking of event announcements or other layouts with a focus on structured information, automatic line breaking will usually not lead to intended results. We don’t need to worry about that as slabText allows for manually set forced line breaking, too. All you need to do, is fill in the text between this markup:

<span class="slabtext"></span>

You can even preset line breaks using JavaScript. We’ll refer to the following example later on:

1
2
3
4
5
6
7
8
9
var stS = "<span class='slabtext'>",
    stE = "</span>",
    txt = [
        "For one night only",
        "Jackie Mittoo",
        "with special Studio One guests", 
        "Dillinger & Lone Ranger"];
 
$("#myHeader").html(stS + txt.join(stE + stS) + stE).slabText();

If you’re puzzled as to where the problem might lie, let’s take a look at an eye-catching heading. The first variant is based on the automatically calculated line breaking of slabText, whereas the second alternative shows forced line breaking depending on manual settings. I think you’ll agree that the second variant is much more attractive, readable, world-changing, what else:

slabText’s proposal: Not optimal under communication aspects

Manually set line breaks transport the important information way better

Using the function viewpointBreakpoint, we are able to define the minimum resolution for the plugin to be invoked. You’ll usually not want to have scaled heading if your browser’s viewpoint is below a certain resolution, say 300 to 400 pixels in width. With the definition of a breakpoint, slabText stays completely idle (if invoked in the defined range), whereas it interprets all other resolutions responsively.

Important note for web font users: Make sure all fonts are loaded before you fire up slabText. The product’s website doesn’t stick to this rule, but intentionally. The developer wants you to see the untouched heading for a short period of time before slabText goes into effect. Live websites shouldn’t risk to work that way.

slabText is under active development. The latest changes happened only a few days ago. slabText can be used free of charge under a MIT-/GPL-license.

Related Links:


IP address-independent access to Mac virtual hosts from Parallels virtual machines

Like many other Mac-using web developers I use Parallels Desktop for testing in various versions of Internet Explorer. It works well, including accessing local development sites set up as virtual hosts in Apache on my Mac.

One thing that’s been bothering me for a long time, though, was that whenever my Mac got a new IP address I had to open the hosts file in all my virtual machines and enter that address to access my sites. Pretty tedious. Well, I recently found out that this can be avoided. In case there are others who didn’t know this and wasted their time editing hosts files, here’s how.

Read full post

Posted in , .

Copyright © Roger Johansson


A Guide To iOS SDK For Web Designers // App development


  

As a designer looking to broaden your skill set, you’ve decided that learning to make native apps for Apple’s iOS platform is an attractive and potentially lucrative prospect. With a frisson of excitement, you start to do some research. The euphoria is short-lived however, as you quickly discover that unless you are an experienced programmer, the task is far from easy.

The documentation provided by Apple is aimed at those with a degree in computer science. Books on iOS development ask that you have a good grasp of Objective-C from the opening page. Online tutorials vary in quality, with many appearing out of date or contradictory.

This post will help you get to know the iOS SDK a little better. It leads you through some choreographed steps of iOS app development, even if you have little or no programming knowledge. It covers some key principles and applies these directly to something useful and relevant: the creation of a simple but functioning portfolio app for the iPhone.

The result will look like this:

iOS Portfolio App

Going Native?

By “native� iOS development, we mean using Apple’s software development kit (SDK) and the programming language Objective-C to author apps for the iPhone, iPod Touch and iPad. Before we learn how to do this, it is worth mentioning why we would want to make an app this way, and what the alternatives might be.

In relaxing the App Store’s submission review guidelines in September 2010, Apple made it easier for developers to use third-party frameworks and more familiar languages, such as HTML, CSS and JavaScript, to create apps. Examples of such tools are Appcelerator’s Titanium Mobile, Nitobi’s PhoneGap (acquired by Adobe in 2011) and appMobi’s XDK, among others. In addition to the benefit of using the more familiar Web languages of HTML, CSS and JavaScript to author apps, these methods enable developers to output to other mobile platforms, such as Android and BlackBerry, with minimal rewriting of the source code.

The disadvantage of using third-party tools is that the resulting app will not be quite as efficient as one that is natively authored, and the newest features of the operating system and hardware will not be available, at least until the framework catches up. Each framework also has its own fairly extensive library of functions that have to be learned, along with its own idiosyncrasies, bugs and workarounds. Plus, to publish your app to the App Store, you need to use Apple’s Xcode, the application used to work with the iOS SDK, so limited familiarity with native processes is still necessary.

A few “third way� solutions, such as Cocos 2D for iPhone and PugPig, are also available, allowing you to connect framework files to an Objective-C project for a particular aim, such as to create a game or magazine app. To make use of these and any others that come along in future, you will need a basic understanding of the SDK.

Therefore, if you are interested in developing for the iPhone, iPod and iPad and you accept that whatever authoring method you choose means having to find your way around Xcode, then getting to grips with the native SDK is a recommended first step.

Getting Started

You will need two things to be able to start working with the iOS SDK:

  • A Mac, running the latest version of OS X (there is currently no way to author natively for iOS on Windows or Linux, although apparently there is a workaround);
  • Apple’s Xcode application.

To get Xcode, download it from the Mac App Store. It’s free but weighs in at nearly 1.5 GB and can take about half an hour to install, so you’ll need to put aside a bit of time to get it up and running.

Preparing Graphics

While waiting for that download to complete, we can look at how you might prepare and export graphics for iOS using Photoshop.

Because all iOS applications have one of two possible pixel densities (standard or Retina), you should aim to work in Photoshop using non-destructive techniques to reduce the need to design twice. This means creating buttons and interface elements using vector shapes and layer styles, and using smart objects for images, where possible. The recommended approach is to work at a Retina-display resolution first, and then scale down to standard resolution once the design is complete. Sometimes you will find that scaling down produces poor results, and you will have to tweak your smaller designs.

Plenty of templates with pre-built iOS system elements are available on the Web. Teehan + Lax has one that is pretty good and widely used. Apart from saving you from having to draw iOS system components from scratch, they also demonstrate how much space is left for content, once elements such as the status, navigation and tool bars are in place.

To set up a new blank iPhone document in an image editor, these are the settings you will need:

  • 640 × 960 pixels,
  • 72 DPI,
  • RGB color mode.

The above is for a Retina display (iPhone 4+ and iPod Touch fourth generation and up). Older devices are 320 × 480 pixels, exactly half the size!

See Marc Edwards’ “Designing for iPhone 4 Retina Display� for more information on iOS design techniques and workflows.

Some Quick Image Exporting Tips

  • iOS accepts a number of image formats, but PNG is recommended because of its support for alpha-transparency and its lossless compression.
  • Graphics for buttons should, in most cases, be exported just as background images, without accompanying text, because this allows for localization (in different languages), accessibility and text resizing between the Retina- and standard-display resolutions.
  • If exporting a button graphic, ensure that the pixels of the actual button are centered in the frame of the exported image, because Interface Builder doesn’t give you precise control over the positioning of button background images or foreground text. You might need to manually compensate for a drop shadow on the opposite sides, for instance.
  • Where possible, flatten design elements made from multiple layers into a single image file. Rebuilding layered UI components in Interface Builder can be a pain; plus, reducing the number of resources that your app uses will make it run quicker and take up less memory. Only interface components that need to respond to user interaction should be animated, and only interface components that will be controlled by the application should be exported as separate image files.
  • You will need to produce Retina and standard versions of every exported image and give them identical names, with a @2x suffix for the Retina version, like so:

    • image.png
    • image@2x.png
  • You can use my SuperSlicr Photoshop action (included in the package) to automate the scaling and exporting of elements from your PSD file.
  • Every pair of images that you make will need a unique and descriptive file name, because they are all stored in the same directory in the app bundle. File names should have only alphanumeric characters (no symbols), and underscores or hyphens instead of spaces. You may use capitalization.
  • Photoshop isn’t very good at compressing PNGs, so run them through porneL’s ImageOptim to reduce their size before importing into Xcode. Xcode will also try to apply its own compression to imported images, which can sometimes increase file size, but this can be disabled.

Xcode Overview

You’ve successfully installed Xcode? Great!

Next, you will need to download and unzip these template files. The package includes a source PSD, some exported PNGs and the required starter code.

In the package, navigate to the folder named Begin Here. Locate the Xcode project document named Portfolio.xcodeproj. Double-click on this file to open it in Xcode.

Once the document has loaded, click on the blue project icon on the left named Portfolio, 1 target, iOS SDK, and you should see a project summary screen in the main Xcode interface, as shown below. We will look at the contents of the summary screen in detail later.

Xcode Overview

The “Navigator� area on the left lists all of the files already associated with your project. These can be expanded out from the blue project icon. We will be mostly interested in those contained in the yellow Portfolio folder, or “group.� Three types of files are here:

  • .h
    A “header� (or interface) file.
  • .m
    A “message� (or implementation) file.
  • .xib
    An “XML interface builder� file, sometimes referred to as a NIB.

The “Editor� area will change depending on what task you are performing. Because we currently have the blue project file selected in the navigator, we are given the “Target Summary� screen. This gives us some basic options for our app, including which device types, iOS version and display orientation we want our app to support. We can also specify images to use for our app’s icon and launch image, which we will look at in detail later.

Single-click on TestAppDelegate.m. The editor area will now turn into a code editor and display the code contained in this file.

Now single-click on MainWindow.xib in the navigator area. The editor area will display Interface Builder, an integrated graphical user interface (GUI) for putting together the front-end of your application.

Interface Builder Overview

The “Inspector� has some tabbed controls at the top that you will need to be familiar with. The last four are the most important:

Inspector Bar

The other important control is the big “Run� button in the top-left corner of Xcode. Pressing this will compile your project code into an app and then run it in an iOS simulator so that you can see whether it works without having to load it onto an actual device. If you press it now, it should launch the simulator and present you with a big virtual iPhone on your desktop.

The iOS Simulator

The simulator works similar to an actual device. Have a play to see how it behaves. Under the “Hardware� menu, you can select different devices and iOS versions and simulate rotating and shaking the device. Holding alt allows you to pinch and zoom. The home button works, taking you to the springboard where there is even a functioning version of mobile Safari (which, incidentally, is great for testing locally hosted websites).

A more detailed guide to the interface is available in Apple’s “Xcode 4 User Guide.�

Importing Graphics Into Xcode

The template package that you downloaded earlier contains some sample image files. You can either use these or use your own for the next section.

To import images into your project, Control-click on the “Images� group in the project navigator and select “Add Files to ‘Portfolio.’�

Adding Images

Browse to the “PNGs� folder in the downloaded package and select all of the images. Check the “Copy items into destination group’s folder� box, and then click “Add.�

The images have now been imported into your project and are available to Xcode and Interface Builder. You can add more graphics to the “Images� group at any time by following this same process.

Editing The Template Without Writing Any Code

There is a debate in the iOS development community about whether one should build an app purely in code or with XIB files generated by Interface Builder and its GUI. Both methods seem to be supported by Apple, and each project necessitates its own approach. Developers who frown on the use of Interface Builder perhaps overlook the power of this tool, which enables us to establish the structure and outward appearance of our app efficiently and visually. For designers used to working with Adobe’s Creative Suite, this will be (almost) familiar territory. For this reason and because our app will be very “view-based,� we will use Interface Builder to begin with.

First, we will look at setting up some different screens, or “views,� that can be switched using some Tab Bar controls. Click on MainWindow.xib in the project navigator to bring up Interface Builder. In the library, select the “Show the Object Library� tab icon (the one that looks like a cube), and scroll through the list of objects until you find “View Controller.�

View Controller Object

Expand the dock using the circular “Expand document outline� button at the bottom, then drag an instance of the View Controller object from the library onto the “Tab Bar Controller� in the dock. The Tab Bar Controller should expand, showing the View Controller nested inside.

Repeat this process twice more, until you have three View Controllers nested inside the Tab Bar Controller. The canvas area should also show the Tab Bar as having three unnamed tabs.

View Controllers Added To Tab Bar

View Controllers?

If you are wondering what a “View� and a “Controller� are, they are part of something called the “Model View Controller� (MVC) paradigm. This is an approach to programming that separates application data, logic and presentation to make things easier to work with. “Model� refers to the back-end aspect that manages data. “View� refers to the front-end user interface. “Controllers� bridge the front and back ends and enable things to happen in your app. We won’t be working with any stored data in this article, so we will only be encountering Views and their corresponding Controllers.

Creating Classes

We need to create some “classes� to generate each of our views; and because we are new to programming, this requires a bit of explanation first.

In object-oriented programming languages such as Objective-C, classes are used as a way to define elements within the application called “objects.� A class defines the qualities (or properties) that an object may have and what it can do (methods). It can then be asked to generate one or more “instances� of an object based on this definition, and these instances are used to make your application work.

Each of the three views that we want to make are objects, so we need to create some classes to be able to conjure them into existence.

To add a new View Controller class, Control-click on the yellow “Portfolio� folder in the navigator, and select “New File� from the contextual menu. In the sidebar of the options sheet that follows, select “Cocoa Touch,� then “Objective-C class.�

New Objective-C Class

Click “Next.� Then, in the sheet that follows, enter “HomeViewController� in the “Class� field, select “UIViewController� in the “Subclass of� drop-down menu, and ensure that the “With XIB for user interface� box is checked.

Naming New View Controller

Clicking “Next� will give you a save dialogue box. Select the “Begin Here > Portfolio� folder, and then hit “Create.�

Repeat this process for the other two views, naming each class “PortfolioViewController� and “ContactViewController,� respectively.

You can rearrange the order of the files in the navigator by dragging and dropping if you want. It should now look something like this:

View Controllers Added To Project Navigator

Configuring Tabs and Views

Return to MainWindow.xib. Select the first View Controller icon in the dock, then the Identity inspector. Select “HomeViewController� from the “Class� drop-down menu.

Connecting HomeViewController Class

Now go to the Attributes inspector. Type “Home� in the “Title� field, and select “HomeViewController� as the NIB name.

Connecting HomeViewController XIB

Expand the View Controller in the dock and select its “Tab Bar Item.� In the Attributes inspector, set the title as “Home,� and select tab-icon-home.png from the Image drop-down menu. You don’t need to specify the @2x Retina version when selecting images in Xcode because they are called automatically when the application is running.

Customizing Tab Name And Icon

Repeat the above process for the Portfolio and Contact views, choosing the relevant classes, titles and image files.

The color of the tab bar highlight can be changed by selecting the main “Tab Bar� object in the dock, then “Image Tint� in the Attributes inspector. Although custom tints will only show up in devices running iOS 5 or higher, iOS 4 and below will safely fall back to showing the default blue highlight color.

Our views within tabs are now all set up! To check that they are working properly, we’ll need to add some dummy content to each view.

Select HomeViewController.xib in the navigator, then drag a “Label� from the library (at the top of the list) onto the view represented in the canvas. Double-clicking on the label in the canvas will allow you to edit its text. Change it to “Home.�

Adding A Label To The Home View

Repeat this for PortfolioViewController.xib and ContactViewController.xib, naming the labels appropriately.

Now hit the “Run� button, and check out your already functioning tabbed app in the simulator!

App Test With Labels

Adding Graphics And Text To The Views

As with desktop publishing applications, inserting images and text in Interface Builder requires you to make a containing element first. These can be dragged onto the canvas from the library, and they are called “Image View� and “Text View,� respectively. They can be repositioned and resized visually with the cursor, or you can type pixel measurements into the Size inspector for more precise control.

The Attributes inspector allows us to specify an image to place in the Image view. We may only choose from images that have been imported into the project.

The Attributes inspector also lets us set text for the Text view, and it gives us typography controls, a background color-picker and scrollbar options.

Arrange the graphics for HomeViewController.xib. Delete the label, and drag on an Image view from the library, setting its image’s name to home-bg.png and its mode to “Top Left� using the Attributes inspector.

Attributes Inspector Select Image

In the Size inspector, check that the Image view has an X value of 0, a Y value of -20, a width of 320 and a height of 480.

The Size Inspector

Next, position a Text view over top. Editing its content, center-align the text, set the text’s color to white, set a custom font (Snell Roundhand, Regular, 24 pixels), and set the background color to “Clear.�

Attributes Inspector Text View Controls

The result should look like this:

Adding Graphics To Home

Because our views are being placed inside a tab bar interface, we also need to simulate the black strip at the bottom of each view so that we can arrange items with this in mind. To do this, select the main “View� object in the dock. Then, in the Attribute inspector, under “Simulated Metrics,� choose “Tab Bar� from the “Bottom Bar� drop-down menu:

Simulated Metrics

This won’t actually add a tab bar to our view. It simply provides a visual reference to help us position the layout.

Now, have a go at arranging the graphics and text for the Portfolio and Contact views. Either use the sample images at the top of this article, or refer to the source PSD provided in the template package.

When creating the thumbnail images in the Portfolio view and the social media buttons in the Contact view, use the “Round Rect Buttons� from the library instead of Image views. If you set the button type to “Custom� in the Attributes inspector, you can then set the button’s image in the same way as you would for an Image view. Set the button size in the Size inspector based on the image’s original dimensions. Using a “Round Rect Button� instead of an Image view allows us to add interactivity to them later.

Now, build and run to check that everything works OK in the simulator.

Extra Finesse

If you press the simulator’s home button, you will notice that your app has an uninspiring white icon on the springboard and a blank screen when it relaunches. Let’s fix that now.

Clicking on the blue “Portfolio� project icon in the navigator will take you back to the summary screen. Scrolling to the bottom of this screen will reveal empty wells awaiting custom images. Adding images is simply a case of dragging them from the Finder to the relevant well.

App Icon And Launch Image Wells

You will find the images you need for this project in the “App Icons� directory in the downloaded package.

If you want to make your own app icon, the images need to conform to the following sizes:

  • Standard: 57 × 57 pixels,
  • Retina: 114 × 114 pixels.

The launch images need to be the same as the display’s overall dimensions:

  • Standard: 480 × 320 pixels,
  • Retina: 960 × 640 pixels.

You will at a later date need some more sizes to display your app correctly in various contexts. An excellent resource detailing the required sizes has been produced by Neven Mrgan. Apple’s “iOS Human Interface Guidelines� also give a good breakdown and include icon and launch image sizes for the new iPad.

iOS automatically rounds the corners of your app’s icon and overlays the standard glossy sheen on it, too, so you don’t need to include these elements in your design.

If, however, you want to create your own non-standard glossy effect or you don’t want gloss on your icon at all, then check the “Prerendered� box to the right of the App Icon wells.

Icon Prerendered Example

To change the name that appears below the icon, select the “Info� tab next to the “Summary� tab at the top of the editor. This will reveal an editor for the app’s .plist (property list) file, which is an XML document containing the main settings for your app:

App Info Plist

Some of the information here, such as “Main nib file base name,� points to resources required by the app when it first launches. Other information, such as “Bundle Identifier,� is used in the black art of provisioning and uploading to iTunes Connect for distribution on the App Store.

To change the name below the icon, change the “Bundle display name� value from ${PRODUCT_NAME} to whatever you want.

The Minor Miracles Of The Xcode Assistant Editor

When we test our app, the custom buttons will respond to being tapped but won’t actually do anything. To make them work, we’ll need to write some code. Luckily, something called the Assistant Editor can help us with the first part of this process.

Select ContactViewController.xib from the navigator. Then, press the “Assistant Editor“ button in the top right of the Xcode window.

Assistant Editor Toggle

This will display an Interface Builder window detailing ContactViewController.xib, alongside a Code Editor window, which shows the associated ContactViewController.h interface document. In the example below, the dock has been minimized, and the Utility area hidden to give the two editors more room. The Code Editor is also using the “Duskâ€� theme, which can be found under “Fonts and Colorsâ€� in Xcode → Preferences.

The Assistant Editor In Action

Miracle 1: Declaring Properties and Methods

Features of a class generally fall into two main types: a “property,� which is a characteristic that the class might possess, and a “method,� which is something that it can do. When adding a button to ContactViewController, we need to declare the button as a property of the class and create a method for what happens when the button is tapped by the user.

The .h document should contain the following code:

#import <UIKit/UIKit.h>
@interface ContactViewController : UIViewController
@end

The #import statement at the top gives the class access to the required iOS user interface classes stored within the UIKit framework.

The @interface declaration starts by defining ContactViewController and stating that it is a subclass (meaning that it inherits all the features) of the UIViewController class, which is defined within UIKit.

We can add in extra items between the opening @interface declaration and its @end, to build on the foundation provided by the UIViewController class.

To do this, Control-click on our orange “WWW� button on the canvas in Interface Builder, drag the cursor to be just above @end in the code editor, and then release. A little dialogue box will pop up with some settings:

Outlet Dialogue

Check that the “Connection� is set to “Outlet,� type in the name websiteButton, and then press “Connect.� Xcode will insert a line of code into the .h document for you.

Repeat the process, this time changing “Connection� to “Action� and providing the name openWebsite.

Action Dialogue

The code in your .h document should now look like this:

#import <UIKit/UIKit.h>
@interface ContactViewController : UIViewController
@property (retain, nonatomic) IBOutlet UIButton *websiteButton;
- (IBAction) openWebsite:(id)sender;
@end

So, what does this all mean?

The @property declaration states that the ContactViewController class has a property. It begins with some parameters: retain, which has to do with memory management (more on this later), and nonatomic, which means that it is not “multithreaded,� something that is common to all iOS properties. Next, there is a definition for the property return type, IBOutlet, which allows us to bind our code to the button we created in Interface Builder. UIButton states that the property will inherit from the UIButton class, defined within UIKit, and then the name of our property is given, which is websiteButton.

The second line of code is a method declaration. It starts by saying that it is an IBAction, which again lets us bind the code to the button object in the XIB. Then it is given a name, in this case, openWebsite. The (id)sender parameter tells us which object called the method. This is handy in certain situations, although we don’t need it right now.

You might have noticed that when we created our View Controller classes, their names began with an uppercase letter, whereas the names we gave our property and method didn’t. This is an Objective-C naming convention and should be adhered to.

Hand-coding those two lines is possible, but using the Assistant Editor to do it saves a bit of time and ensures that the syntax is correct. It also performs a whole series of other tasks for us as well. Let’s look at what else it does.

Miracle 2: Property Synthesis and Memory Management

Return to “Standard Editor� mode, and select ContactViewController.m. Around line 12, you should see this directive that the assistant has put in for us:

@synthesize websiteButton;

This will ask the compiler to “synthesize� some extra methods for us when the app is built, for setting and getting variables for our property. This all happens behind the scenes and saves us from having to deal with even more code, so it really is useful.

Lower down, we find the following:

- (IBAction)openWebsite:(id)sender {
}

This is the method implementation for our button action. In a minute, we will put some code in there to make our button work.

You should also find another method implementation that looks like this:

- (void) dealloc {
[websiteButton release];
[super dealloc];
}

This method has to do with memory management and is defined within the Cocoa framework, which is why we haven’t needed to mention it in our interface.

Managing memory is very important when programming because a mobile device doesn’t have much to play with. When the websiteButton property is defined, a chunk of memory is allocated to it using the retain command. This command asks iOS to reserve a bit of memory for the button until we tell it to let it go. The dealloc method is activated only when the View instance is destroyed; so, by putting websiteButton release in there, we are asking iOS to free up the memory set aside for the button when this event occurs. If we don’t do this, then the memory keeps getting allocated, even when the button object isn’t in use anymore. This is called a “memory leak.� If left unchecked, these leaks will add up, affecting the app’s responsiveness and the device’s battery life and causing all sorts of other horrors!

Thankfully, once again, the assistant editor has set this all up for us, so we don’t need to remember to do it. Hooray!

It is probably worth mentioning that version 5 of the iOS SDK comes with “Automatic Reference Counting� (ARC), which seeks to further automate memory management for iOS developers. When creating a new project, you have the option to turn ARC on and off. We are not using ARC in this project, so we can learn a bit about how memory management works. Integrating freely available components found on the Internet (many of which are written using manual reference counting) with an ARC-enabled project can also be difficult. With each subsequent release of the SDK, however, Apple is pushing more and more for developers to embrace ARC, and there are many advantages in doing so. ManiacDev has compiled some useful resources to make this transition smoother.

Miracle 3: Code Binding

The Assistant Editor has also connected our code to the button object in the XIB. Select ContactViewController.xib, expand the dock, and under “Placeholders� select “File’s Owner.� This represents the ContactViewController class. Now, select the Connections inspector. It should look like this:

Connections Inspector

Under “Outlets,� we can see the websiteButton property linked to the Button XIB object.

Under “Received Actions,� we can see that the openWebsite method is also connected to the Button.

Under it, there is also an associated event, “Touch Up Inside.� This means that the method will be called when the user touches and then releases their finger while still inside the button. This is the default touch event.

Handwriting Your First Bit Of Objective-C

Lets make that button do something!

Change the openWebsite method implementation in ContactViewController.m so that it looks like the following:

- (IBAction)openWebsite:(id)sender {
NSURL *webAddress = [NSURL URLWithString:@"http:www.mightymeta.co.uk"];
[[UIApplication sharedApplication] openURL:webAddress];
}

The syntax for a method is fairly straightforward. Simply provide the name of the method, and then put what you want to happen when the method is called between the pair of curly braces.

In this case, we are doing two things. First, we are creating a temporary variable named webAddress and assigning it a string of text that contains our email URL.

It is worth noting that this is something called a “convenience method.� It creates an instance of the NSURL class and automatically allocates some memory to it. It also sorts out the memory deallocation for you, so you don’t have to worry about releasing the webAddress variable.

The second line asks the OS to open the URL in a relevant application, which in this case would be the default Web browser.

Build and run to test whether it works.

To make the other buttons work, simply repeat the steps that we went through to create this button. Any mailto: URLs will work and will launch the default mail client. To make a phone call, put tel:, followed by the number you want to dial in place of the URL. You can change the name of the temporary variable to suit the purpose for each button.

Making a View Appear Modally

The portfolio section currently has some thumbnail images. Wouldn’t it be great if the user could tap on these to get bigger versions?

This can be achieved by creating what is called a “Modal View.� This is essentially a new view that is placed over top the previous one, and it comes with a range of animated transitions into view.

Create the Modal View

Modals are easy to create. First, generate a new class called BigImageViewController (Control-click on the “Test� folder in the project navigator, select “New File� and then the UIViewController subclass).

Open the corresponding XIB in Interface Builder, add an Image view that fills the entire view, and set its image as portfolio-modal-bg.png. Add a custom Round Rect button, give it a background of button-close.png, set the color of the “Close� title to white, and place it in the top-left corner.

Next, place another image view over top the first. Fit it to near the edges of the paper background, but don’t assign an image to it:

Creating A Modal View

Use the Assistant Editor to declare the empty Image view as an outlet named imageFrame, and connect the button to an action named closeView in BigImageViewController.h (you can select which file the right-hand window will display from the bar at its top):

@property (retain, nonatomic) IBOutlet UIImageView *imageFrame;
- (IBAction)closeView:(id)sender;

Then type the following into the closeView method in BigImageViewController.m:

- (IBAction)closeView:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}

This code will close the modal view when the button is tapped.

Code for Launching the Modal

Now, using the Standard Editor, type in PortfolioViewController.h so that it looks like the following example:

#import <UIKit/UIKit.h>
#import "BigImageViewController.h"
@interface PortfolioViewController : UIViewController
@property (nonatomic, retain) UIImage *bigImage;
- (IBAction) selectImage1;
- (void) openBigImageView;
@end

Make sure to include the #import statement for the BigImageViewController header file. This is required so that we can send a message to this class and ask it to create an instance of itself.

A property and two method declarations are there. The second, openBigImage, doesn’t need to be connected to any objects in the XIB; so, it has a return type of (void), meaning… well, a big black hole of nothingness.

We haven’t used the Assistant Editor here because we are doing something a little different from before. Because of this, we need to manually synthesize and release the bigImage property at the start of PortfolioView.m, like so:

@implementation PortfolioViewController
@synthesize bigImage;
- (void) dealloc {
[bigImage release];
[super dealloc];
}

Underneath the dealloc method, implement the two methods that we declared in the header:

- (IBAction) selectImage1 {
self.bigImage = [UIImage imageNamed: @"image1-big.png"];
[self openBigImageView];
}
- (void) openBigImageView {
BigImageViewController *bigImageView = [[[BigImageViewController alloc] initWithNibName:@BigImageViewController bundle:nil] autorelease];
bigImageView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:bigImageView animated:YES];
[bigImageView.imageFrame setImage:bigImage];
}

Wow, that’s a lot to take in. Lets go through it.

The selectImage1 method sets the bigImage property to the image file that we want to use, and then calls the openBigImageView method.

The openBigImageView creates an instance of the BigImageViewController class named bigImageView, presents it as a modal using the “flip� transition style, and then sends its imageFrame the image file held by the bigImage property.

Because we have manually allocated memory to the instance of BigImageViewController, we need to release it at some point, but we don’t know how long the object will be needed for because it depends on how long the user keeps the modal active. The autorelease command helps us with this problem because it asks iOS to hold on to the memory for a bit and then release it later on, when it is deemed safe to do so.

Manual Code Binding

Now we need to connect our code to the objects in the XIB. Select PortfolioViewController.xib, and then the “File’s Owner� object in the dock, and then the Connections inspector.

Under “Received Actions,� you will find the selectImage1 method, and an empty circle to the right of it. Click and drag a connection from this circle over to the relevant thumbnail button:

Binding A Button To Code Manually

Select “Touch Up Inside� from the list of button events that appears.

Build and run to see whether it works. If everything is in place, you should be able to tap the thumbnail to reveal the bigger image.

See if you can work out how to do the same for the other images on the portfolio page. You will need to create selectImage2, selectImage3 and selectImage4 methods, but you won’t need another openBigImage. You could also try using different transition styles; you have four to choose from:

  • UIModalTransitionStyleCoverVertical
  • UIModalTransitionStyleCrossDissolve
  • UIModalTransitionStyleFlipHorizontal
  • UIModalTransitionStylePartialCurl

If you get really stuck, have a look at the completed project in the “End Result� folder of your downloaded template package.

In Conclusion

We’ve covered quite a lot of ground, having looked at the basics of the Xcode interface and how to arrange visual elements in Interface Builder. We’ve also been introduced to the key concepts of classes, properties, methods and memory management in Objective-C.

In the process, we have built a functioning, albeit limited, app. Making it ready for submission to the App Store would require a unique design and some additional functionality, such as adding Tweets to that empty speech bubble on the home page. Now that you have a grasp of the basics, take advantage of the great resources out there to help you with this next step.

Further Reading And Resources

App Design

App Development

  • “Learn Objective-C,â€� Cocoa Dev Central
    A summary of the basics of Objective-C.
  • Cocoa Controls
    Open-source UI components, such as carousels, maps and Twitter aggregators, to integrate in your project.
  • ManiacDev.com
    iOS libraries, controls, tutorials, examples and tools, many of which are open source.
  • Baker Ebook Framework and PugPig
    These enable you to build an interactive book or magazine using HTML5 and then wrap it into an app using Xcode.
  • Creator, GameSalad
    Want to make a promotional iPhone game using drag-and-drop behaviors and your new-found Xcode skills? Then GameSalad’s Creator is for you.

(al)


© James Brocklehurst for Smashing Magazine, 2012.


Ways to embed a Clickable SVG-Logo into Your Website


  

With the growing number of screen resolutions, devices that support an internet connection (desktop computer, laptops, but also tablets, mobile, TVs, and even your fridge someday), flexibility and scalability has become more and more important for websites. With the new arrival of the Macbook Pro Retina, this went a step further and brought an HiDPI display that was unknown to the market. This means a whole new challenge for web designers who have to find new ways to handle and make images size more flexible to avoid blurry rasterized effects. In this article, we will see how the SVG-format can help us solve this challenge, using an everyday example of a website header with a clickable logo.

My personal roadmap to this project: What I wanted to achieve

From a UX / code point of view,  I wanted two things for my logo:

  • Since it’s the logo of my brand, I wanted it to be clickable so that users can easily go back to the homepage
  • I’m a nice girl and don’t want to penalize people with older browsers, so I wanted to provide some PNG-fallback for our older friends. If possible, the fallback should work without JavaScript.

Taking a look at these two things, I ran some tests, and found a few different code variants to achieve this result. They proved not equally successfull though. Following I’ll show you how good the alternatives will perform.

Here is a visual of what we will build:

SVG final product

You can see a demo here, or fork the code on github

You can take a look at this table to see the SVG support in browsers.

The SVG logo: what is this format, and how did I create it?

SVG stands for Scalable Vector Graphics. It is a markup language that enables us to create two-dimensional graphics that are fully scalable.  It is based on an XML syntax, so you can create and open a SVG file in a text editor. Don’t panic, you don’t need to be a hardcore developer to do so.  http://raphaeljs.com/ for example is a very nice library to generate SVG images in an easier way.

If you’re a designer, you can use your favorite design software to create SVG files. Illustrator and Inkscape will do the job nicely and even Fireworks has a little plugin http://fireworks.abeall.com/extensions/commands/Export/ for this task.

Save as SVG with Illustrator

Save a SVG logo with Ilustrator using save as > svg inside the format dropdown

Just remember a few rules when creating a SVG logo:

  • Don’t use complex illustrator gradients, only linear and radial ones
  • Don’t use the photoshop effects provided in Illustrator
  • Be careful and name layers and group layers
  • Always merge shapes in the end when using pathfinder.
  • Transform text into vectors shapes to make sure the result will work on devices that don’t have the font.

To sum it up : Keep your SVG drawing as simple as possible, export it, and test in different browsers to see the result.

For my example, I’m using a simple SVG-logo with no gradients and plain colors. (Many thanks to Geeks and the City for letting me kindly use their logo in this example. The logo is their property, I only use it for the example with their consent. You can re-use the code for your projects, but not the logo.)

1. The < object > embed solution

This is the historical solution to embed SVG in webpages. The big advantage of this method is that the fallback is easy to provide, you simple have to add the .png image in an img tag :

See demo

The code :

1
2
3
4
5
6
7
8
9
<a href="#" >
 
<object class="logo" data="logo.svg" width="186" height="235"&nbsp; type="image/svg+xml">
 
<img src="logo.png" width="186" height="235"&nbsp; alt="Logo Geeks and the City" />
 
</object>
 
</a>

Pros:

  • The fallback is simple to provide
  • The fallback does not rely on JavaScript

Cons :

  • The link is not displayed on browsers that support SVG, you have to add a display:block to the link. Then the link is hidden “behindâ€� the SVG object, so you can’t click on the logo but around it
  • Modern browsers with SVG support will download both files SVG and PNG

2. The <svg> tag solution with foreignObject as fallback

Since HTML5, you can use a  the new <svg> tag.  Remember when I said that SVG was a markup, you can simply copy the markup inside the SVG tag. All you have to do is open the .svg logo in a text editor, and copy paste the code.

In the foreignObject, we will include an img-tag with the .png fallback

See demo

The code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<a href="#svg_technique" >
 
<svg&nbsp; class="logo" width="186" height="235">
 
<g id="nyt_x5F_exporter_x5F_info">
 
</g>
 
<g id="nudged">
 
<path style="fill:none;stroke:#000000;stroke-miterlimit:10;" d="M46.397,121.92"/>
 
……
 
<foreignObject width="0" height="0" overflow="hidden">
 
<img src="logo.png" width="186" height="235"&nbsp; alt="Logo Geeks and the City" />
 
</foreignObject>
 
</svg>
 
</a>

Pros

  • The link now works
  • The fallback works without JavaScript activated

Cons :

  • Due to the copy/pasting of the SVG code, this technique is not very flexible, especially for logos. Every time you change it, you have to upload the code
  • Not all browsers implement the syntax correctly since it’s pretty new

3. The <img> solutions, with different fallbacks

A last way of embedding SVG files is to use the img-tag. Note that the tag was not created for this purpose, so you might encounter problems if you use many JavaScripts to modify your SVG object.

a. The <img> solution with JavaScript on error-fallback

Credits where due, I found this technique on Tavmjong Bah’s blog (a great read if you want to go deeper into the SVG manipulation techniques using JavaScripts). This solution suggests using the error handler to detect the SVG support, and replace the .svg by a .png logo when the browser does not support SVG and triggers and error.

See the demo

The code

1
2
3
4
5
<a href="#catching_error" >
 
<img class="logo" src="logo.svg" alt="A sample SVG button." width="186" height="235"&nbsp; alt="Logo Geeks and the City" &nbsp;onerror="this.removeAttribute('onerror'); this.src='logo.png'" />
 
</a>

 

Pros

  • The link works pretty well
  • The code is very simple and we only need one img-tag

Cons

  • The fallback relies on JavaScript and does not work if deactivated

b. The <img> solution with a CSS background fallback

For this technique, we will only provide the SVG image in the HTML, and instead use Modernizr to detect SVG support. If the SVG is supported, the script will add a .svg class to the html, if not, it will add a .no-svg.

See the demo

The HTML code

1
2
3
4
5
<a href="#modernizr_css_fallback" >
 
<img class="logo" src="logo.svg" width="186" height="235"&nbsp; alt="Logo Geeks and the City" />
 
</a>

The CSS code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*** specific for fallbacks **/
 
#modernizr_css_fallback img.logo {
 
display:none;
 
}
 
#modernizr_css_fallback a{
 
display:block;
 
width:186px;
 
height:235px;
 
background-image: url(logo.png);
 
background-color:transparent;
 
text-indent:-999px;
 
color:transparent;
 
margin:0 auto;
 
}
 
.svg #modernizr_css_fallback img.logo {
 
display:block;
 
}
 
.svg #modernizr_css_fallback a{
 
background: none;
 
}

This one gets a little tricky, let’s explain it. In order to make this work without JS activated, we will not use the .no-svg class. First we will hide the image for one simple reason: Internet explorer 8 and browsers that don’t support SVG will otherwise display the title of the img. If we put the background on the img-tag, we will see both the background, and the alt-attribute displayed above.

alt tag shown on IE

Internet explorer shows the alt-tag on top of the background

Instead, we hide the image, and put the background PNG-file in the a-tag.

Now, if SVG is supported, we get the .svg class in the html-tag, and do it all the way around: We display the img-tag, with the SVG in it, and hide the CSS background of the a-tag.

Pros:

  • The link works
  • The fallback works without JavaScript

Cons:

  • Not really a con, but we have to cheat and apply the background to the a-tag
  • If JavaScript is deactivated, browsers that do support SVG will get the PNG-fallback.

c. The <img> method with modernizR SVG detection to provide data-fallback fallback

In this method, we will use the new HTML5 data-attributes to provide the fallback file, coupled with modernizr to swap the image for browsers that do not support SVG.

See demo

The HTML code:

1
2
3
4
5
<a href="#img_modernizr_js_remplacement_bis" >
 
<img class="logo" src="logo.svg" alt="A sample SVG button." width="186" height="235" data-fallback="logo.png"&nbsp; alt="Logo Geeks and the City" />
 
</a>

The JavaScript code:

1
2
3
4
5
6
7
8
9
10
11
window.onload = function(){
 
if(!Modernizr.svg) {
 
var imgs = $('img[data-fallback]');
 
imgs.attr('src', imgs.data('fallback'));
 
}
 
}

Using modernizr, we detect the SVG-support. If the SVG is not supported, we replace our logo with a .png one, using JavaScript.

Pros

  • The link works
  • The code is simple and clear

Cons

  • The fallback relies on JavaScript and does not work if it is deactivated

d. The <img> method with JavaScript and < noscript > as fallback

Once again, we use the image-tag, but this time, we will provide a noscript-tag with the .png-image in it, in case JavaScript is deactivated.

See demo

The HTML code:

1
2
3
4
5
<a href="#img_modernizr_js_remplacement_nojs">
 
<noscript><img class="logo" src="logo.png" alt="A sample SVG button." width="186" height="235" alt="Logo Geeks and the City" /></noscript>
 
</a>

The JavaScript code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
window.onload = function(){
 
if(Modernizr.svg) {
 
$('#img_modernizr_js_remplacement_nojs .header a').html('<img src="logo.svg" width="186" height="235" alt="Logo Geeks and the City"/>');
 
}
 
else {
 
$('#img_modernizr_js_remplacement_nojs .header a').html('<img src="logo.png" width="186" height="235" alt="Logo Geeks and the City">');
 
}
 
}

We detect SVG-support, swap the image for the SVG-logo if supported, and the PNG if not.

Pros

  • The link works
  • Works with JavaScript desactivated

Cons

  • If JavaScript is deactivated, browsers that support SVG will display the noscript PNG-fallback.

Going further: font-icon and htaccess-trick for the road

In this article, I did not mention the font-icon embedding-technique. You can see the Icon Fonts are Awesome page to have a little demo, and find a nice list of icons here. I did not use this technique, because I thought it was not very appropriate and creating a font just for a simple logo was maybe “too muchâ€�.  Also, logos should be images (in the wild sense, I include SVGs into images here), so using a font-icon for a logo on a website was not a solution in my opinion.

Also note that you might have to declare the SVG-format in the .htaccess so that the server delivers the correct header. You can do so by adding this to the .htaccess:

1
2
3
AddType image/svg+xml svg svgz
 
AddEncoding gzip svgz

More on SVG-usage from around the web:

Conclusion

In this article, we saw different techniques to embed a SVG-logo, with a link back to the homepage of the site. I’m not telling you that one method is better than the other, you will have to choose. At the moment, I’m using the last solution on the live website I did this research for, but that’s just personal preferences. There must also be other solutions to achieve this and I would be glad to hear about how you manage this challenge, so don’t hesitate to share your results in the comments! So, will you try to use some SVG logos on your website soon? What is your favorite technique?

(dpe)


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress