Archive for category coding

Entering The Wonderful World of Geo Location

Smashing-magazine-advertisement in Entering The Wonderful World of Geo Location
 in Entering The Wonderful World of Geo Location  in Entering The Wonderful World of Geo Location  in Entering The Wonderful World of Geo Location

I thought I could not be out-geeked. With a background in radio, and having dabbled in the demo scene on the Commodore 64 and hung out on BBSes and IRC for a long time and all the other things normal kids don’t quite get, I thought I was safe in this area.

Then I went to my first WhereCamp, an unconference dealing with geographical issues and how they relate to the world of Web development. Even my A-Levels in Astronomy did not help me there. I was out-geeked by the people who drive and tweak the things that we now consider normal about geo-location on the Web.

Pulling out your phone, find your location and getting directions to the nearest bar is easy, but a lot of work has gone into making that possible. The good news is that because of that effort, mere geo-mortals like you and me can now create geographically aware products using a few lines of code. So, let’s give the geo-community a big hand.

[By the way: The network tab (on the top of the page) is updated several times a day. It features manually selected articles from the best web design blogs!]

Why Geo Matters

First of all, why is it important to consider physical location on this planet (at this moment) when we develop Web products? There are a few answers to this.

The first answer is mobility. The days of people sitting in front of desktop machines at home are over. Sales of mobile devices, laptops and netbooks have overtaken those of bulky stationary computers in the last few years. The power of processors now allows us to use smaller, more mobile hardware to perform the same tasks. So, if people use their hardware on the go, we should bring our systems to them. Which brings us to the second—very important—point: relevance.

Giving the user content that is relevant to the physical space they are in at the moment makes a lot of sense. We are creatures of habit. While we love the reach of the Internet, we also want to be able to find things in our local area easily: people to meet, cafes to frequent, interesting buildings and museums to learn about. The advertising industry—especially of the adult and dating variety—realized this years ago. I am sure you have come across one of the following before:

Adultpersonals in Entering The Wonderful World of Geo Location

I am sure these ads are more successful than the ones that show only user names. That the photos and names are the same for every location doesn’t seem to be a problem (but yes, I noticed it). So how does it all work?

Getting The User’s Location Via IP

Every computer on a network has a number that identifies it: its IP address. The Internet is nothing but a massive network, and your IP number is assigned to you by the service provider that you have used to connect to that network. Because the numbers that service providers assign change from one geographical location to the next (much like telephone numbers), you can make quite a good estimate of where your visitors are from.

To find out where a certain phone number is from, you use a phone book. To find out where an IP is from, you can use the Maxmind GeoIP database. Maxmind also provides a JavaScript solution that you can use on websites:

<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script>
  var info = document.getElementById('info');
  var lat = geoip_latitude();
  var lon = geoip_longitude();
  var city = geoip_city();
  var out = '<h3>Information from your IP</h3>'+
            '<ul>'+
            '<li>Latitude: ' + lat + '</li>'+
            '<li>Longitude: ' + lon + '</li>'+
            '<li>City: ' + city + '</li>'+
            '<li>Region: ' + geoip_region() + '</li>'+
            '<li>Region Name: ' + geoip_region_name() + '</li>'+
            '<li>Postal Code: ' + geoip_postal_code() + '</li>'+
            '<li>Country Code: ' + geoip_country_code() + '</li>'+
            '<li>Country Name: ' + geoip_country_name() + '</li>'+
            '</ul>'
  info.innerHTML = out;
</script>

Geolocation in Entering The Wonderful World of Geo Location

This gives you some information on the user (try it out for yourself). The challenge, though, is relevance. Your IP location is the location of the IP that your provider has assigned to you. Depending on your provider, this could be quite a ways off (in my case, I live in London, but my provider used to show me as living in Rochester). Another problem is if you work for a company that uses a VPN. At Yahoo, for example, I have to connect to the VPN to read my company email, and I have to choose a location to connect to:

Vpn in Entering The Wonderful World of Geo Location

So, for a solution like the one highlighted above, I would show up as being in a totally different part of the world (which might be useful for watching Internet TV in the UK while I am in the US). IP geo-location, then, is an approximation, not a dead-on science.

Getting The User’s Location Via The W3C Geo API

Guessing geographical location via IP is possible, but it can also be pretty creepy. Being able to take advantage of your location is useful, but security-conscious users and people who are generally suspicious of the Internet are not happy with the idea of their movements being monitored by a computer. This makes sense: if I can monitor your whereabouts day and night, I would know where and when to rob your house without you being there.

There are a lot of solutions to the challenge of having good-quality geo-location and maintaining privacy. Google Gears has a geo-location service; Plazes helps you store your location; and Yahoo’s Fire Eagle is probably the most polished way to securely maintain your location on the Web.

The problem with all of these services is that they require the user to either install a plug-in or visit a Web service to update their location. This is not fun; browsers should do the work for you.

We now have a W3C recommendation for a geo-location API that allows browsers to request the geographical location of the user. This makes it less creepy, and you get real data back.

Firefox 3.5 and above supports the W3C geo-location API. So does Safari on the iPhone if you run OS 3.0 or above. If you use the API, the browser will ask the user whether they want to share their location with your website.

Geowarning in Entering The Wonderful World of Geo Location

Once the user allows you to get their location, you get much more detailed latitude and longitude values. Using the API is very easy:

// if the browser supports the w3c geo api
if(navigator.geolocation){
  // get the current position
  navigator.geolocation.getCurrentPosition(

  // if this was successful, get the latitude and longitude
  function(position){
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
  },
  // if there was an error
  function(error){
    alert('ouch');
  });
}

Compare the IP and W3C solutions side by side. As you can see, there can be quite a difference in measuring the visitor’s location. The extent of the difference is shown in the following demo:

Difference in Entering The Wonderful World of Geo Location

Converting Latitude And Longitude Back Into A Name

Having more information is nice, but we have lost the name of the city and all the other nice data that came with the Maxmind database. Because the location has changed, we cannot just grab that old data; we have to find a way to convert latitude and longitude coordinates into a name. This process is called “reverse geo-coding,” and several services on the Web allow you to do it. Probably the most well-known is the geo-names Web service, but it has a few issues. For starters, the results are very US-centric.

One freely available but lesser-known reverse geo-coder that works worldwide comes from a surprising source: Flickr. The flickr.places.findByLatLon service returns a location from a latitude and longitude coordinates. You can try it out in the app explorer, but by far the easiest way to use it is by using the Yahoo Query Language (or YQL). YQL deserves its own article, but let’s just say that, instead of having to authenticate with the Flickr API and read the docs, reverse geo-coding becomes as easy as this:

select * from flickr.places where lat=37.416115 and lon=-122.0245671

Using the YQL Web service, you can get the result back as XML or JSON. So, to use the service in JavaScript, all you need is the following:

<script type="text/javascript" charset="utf-8">
 function getPlaceFromFlickr(lat,lon,callback){
   // the YQL statement
   var yql = 'select * from flickr.places where lat='+lat+' and lon='+lon;

   // assembling the YQL webservice API
   var url = 'http://query.yahooapis.com/v1/public/yql?q='+
              encodeURIComponent(yql)+'&format=json&diagnostics='+
              'false&callback='+callback;

   // create a new script node and add it to the document
   var s = document.createElement('script');
   s.setAttribute('src',url);
   document.getElementsByTagName('head')[0].appendChild(s);
 };

 // callback in case there is a place found
 function output(o){
   if(typeof(o.query.results.places.place) != 'undefined'){
     alert(o.query.results.places.place.name);
   }
 }

 // call the function with my current lat/lon
 getPlaceFromFlickr(37.416115,-122.02456,'output');
</script>

Combine that with the other services, and we get a more detailed result and can put a name to the coordinates:

Reversegeocode in Entering The Wonderful World of Geo Location

The Trouble With Latitude And Longitude

While latitude and longitude coordinates are a good way to describe a location on Earth, it is also ambiguous. The coordinates could represent either the centre of a city or a point of interest (such as a museum or a pub) in that spot.

WOEID to the Rescue

To work around the problem, Yahoo and Flickr (and soon will Twitter) support another way to pinpoint a location. The Where On Earth Identifier (or WOEID) is a more granular way to describe locations on Earth. Because Flickr supports it, we can easily get get photos from a particular area:

select * from flickr.photos.search where woe_id in (
  select place.woeid from flickr.places where lat=37.416115 and lon=-122.02456
)

Using this and a few lines of JavaScript, showing geo-located photos is pretty easy:

Geolocated-photos in Entering The Wonderful World of Geo Location

This has also been wrapped in a simple-to-use YQL solution. The following code will display 10 photos of Paris:

<script>
  function photos(o){
    var container = document.getElementById('photos');
    container.innerHTML = o.results;
  }
</script>
<script src="http://query.yahooapis.com/v1/public/yql?q=
select%20*%20from%20flickr.photolist%20where%20location%3D%22paris%2Cfr
%22%20and%20text%3D%22%22%20and%20amount%3D10&format=xml&
env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=photos">

You can also play with this in the YQL console.

Why Not Search For The Location’s Name?

The main question about implementations such as the one above is why couldn’t we just do a search on Flickr for the city, instead of doing all the complex geo-lookups? The reason is false positives. Take Paris, for example: if you want to show photos of Paris on a travel website, you don’t want Paris Hilton to show up in there. Same goes for Jack London. You may also want to show photos of London, England, not London, Ontario. Geographic data is full of these kinds of gotchas, and the term for finding the right one is “disambiguation.” See the Wikipedia article on “Victoria” to see just how many geographical contexts this term can have.

Turning Text Into Geo-Data

Finding a visitor’s geographic location is all well and good, but it doesn’t mean much if you can’t link it to information for that area. This is where it gets tricky. For Flickr (and soon Twitter), this is easy, because both services are able to attach geographical locations to the content you put in them. This is not so for most of the information on the Web, though, and this is when we resort to clever algorithms, machine-learning, pattern-matching and all the other think-tank stuff that computers and the scientists in front of them do.

Say you want to identify the geographical locations that a particular text or Web page talks about. Yahoo offers a service for that called Placemaker, and it is pretty easy to use. You need to get a developer key and send this as appid, send a text as documentContent, define the type of the text as documentType and define the type of data you want back as outputType. All of this needs to be sent as a POST to http://wherein.yahooapis.com/v1/document:

<form action="http://wherein.yahooapis.com/v1/document" method="post">
  <textarea id="text" name="documentContent">Hi there, I am Chris.
    I live in London, I am currently in Sunnyvale and will soon be in
    Atlanta and Las Vegas.</textarea>
  <div><input type="submit" name="sub" value="get locations"></div>
  <input type="hidden" name="appid" value="{YOUR_APP_ID}">
  <input type="hidden" name="documentType" value="text/plain">
  <input type="hidden" name="outputType" value="xml">
</form>

You can try this out yourself. Using PHP to call the API instead of a simple form, you can even format the output nicely. See it in action here:

Placemaker-results in Entering The Wonderful World of Geo Location

While developers who have played around with Web services won’t find Placemaker hard to use, the service can be daunting for the average developer. That is why I built GeoMaker some time ago. GeoMaker allows you to enter a text or URL, select the locations you want to include in the final outcome, and get the locations either as a map to copy and paste or as micro-formats.

Geomaker in Entering The Wonderful World of Geo Location

However, because there is also a YQL solution for using PlaceMaker in JavaScript, we can do the same with a few lines of client-side code to enhance an HTML document. Check out the following example:

Textandmap in Entering The Wonderful World of Geo Location

To use this, you need three things: a text with geographical locations in them in an element with an ID, a Google Maps API key (which you can get here) and the following few lines of code:

<script src="http://github.com/codepo8/geotoys/raw/master/addmap.js"></script>
<script>
addmap.config.mapkey = 'COPY YOUR API KEY HERE';
addmap.analyse('content');
</script>

This makes it incredibly easy to give your visitors a sense of what part of the world a text is related to.

Adding Maps To Your Documents

Online maps have been around for a while now (and Google Maps was instrumental in the rise of AJAX), and many providers out there allow you to add maps to your documents. Google is probably the leader, but Yahoo also has maps, as does Microsoft and many more. There is even a fully open map service called Open Street Maps, which has been instrumental in the recent rescue efforts in Haiti.

If you want interactive maps, probably the easiest thing to use is Mapstraction, which is a JavaScript library that does away with the discrepancies between the various map providers and gives you a single interface for all of them. 24ways published a good introduction to it three years ago.

Probably the simplest way to show a map that supports markers and paths in your document without having to dive into JavaScript is the Google static maps API. It creates maps as images, and all you need to do is provide the map information in the src URI of the image. For example, in the script example above, this would be:

http://maps.google.com/maps/api/staticmap?
sensor=false
&size=200x200
&maptype=roadmap
&key=YOUR_MAP_KEY
&markers=color:blue|label:1|37.4447,-122.161
&markers=color:blue|label:2|37.3385,-121.886
&markers=color:blue|label:3|37.3716,-122.038
&markers=color:blue|label:4|37.7792,-122.42

You can define the size and type of the map. If all you provide is the location of markers, the API will automatically find the right zoom level and area to ensure that all markers are visible. Google’s website even offers a detailed tool to create static maps, including markers and paths.

Geo Is A Space To Watch

I hope this has given you some insight into all of the things you can do to bring the earth to your product and to put your product on the map. Geo-location and geo-aware services are already huge, and they’ll be even more important this year. There will be more services—some mobile providers are ready to roll out new hardware and software—and now you can be a part of it.

What the geo-world needs now is a designer’s eye, and this is where you can help the geo-geeks create apps that matter, that look great and that make a difference in our visitors’ lives. For inspiration, check out Mapumental, which allows you to pinpoint a place to live in London, or see how Google Earth and some 3-D Objects allow you to race a milk truck on real map data.

(al)


© Christian Heilmann for Smashing Magazine, 2010. | Permalink | 53 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags:

Tags:

The Future Of CSS Typography

Smashing-magazine-advertisement in The Future Of CSS Typography
 in The Future Of CSS Typography  in The Future Of CSS Typography  in The Future Of CSS Typography

There has been an increasing and sincere interest in typography on the web over the last few years. Most websites rely on text to convey their messages, so it’s not a surprise that text is treated with utmost care. In this article, we’ll look at some useful techniques and clever effects that use the power of style sheets and some features of the upcoming CSS Text Level 3 specification, which should give Web designers finer control over text.

Keep in mind that these new properties and techniques are either new or still in the works, and some of the most popular browsers do not yet support them. But we feel it’s important that you, as an informed and curious Web designer, know what’s around the corner and be able to experiment in your projects.

[Offtopic: By the way, did you know that Smashing Magazine has a mobile version? Try it out if you have an iPhone, Blackberry or another capable device.]

A Glance At The Basics

One of the most common CSS-related mistakes made by budding Web designers is creating inflexible style sheets that have too many classes and IDs and that are difficult to maintain.

Let’s say you want to change the color of the headings in your posts, keeping the other headings on your website in the default color. Rather than add the class big-red to each heading, the sensible approach would be to take advantage of the DIV class that wraps your posts (probably post) and create a selector that targets the heading you wish to modify, like so:

.post h2 {
	font-weight: bold;
	color: red;
}

This is just a quick reminder that there is no need to add classes to everything you want to style with CSS, especially text. Think simple.

The Font Property

Instead of specifying each property separately, you can do it all in one go using the font shorthand property. The order of the properties should be as follows: font-style, font-variant, font-weight, font-size, line-height, font-family.

When using the font shorthand, any values not specified will be replaced by their parent value. For example, if you define only 12px Helvetica, Arial, sans-serif, then the values for font-style, font-variant and font-weight will be set as normal.

The font property can also be used to specify system fonts: caption, icon, menu, message-box, small-caption, status-bar. These values will be based on the system in use, and so will vary according to the user’s preferences.

Other Font Properties

A few font-related properties and values are not as commonly used. For example, instead of using text-transform to turn your text into all caps, you could use font-variant: small-caps for a more elegant effect.

You could also be very specific about the weight of your fonts, instead of using the common regular and bold properties. CSS allows you to specify font weight with values from 100 to 900 (i.e. 100, 200, 300, etc.). If you decide to use these, know that the 400 value represents the normal weight, while 700 represents bold. If a font isn’t given a weight, it will default to its parent weight.

Another useful property, sadly supported only in Firefox for now, is font-size-adjust, which allows you to specify an aspect ratio for when a fall-back font is called. This way, if the substitute font is smaller than the preferred one, the text’s x-height will be preserved. A good explanation of how font-size-adjust works can be found on the W3C website.

Dealing With White Space, Line Breaks And Text Wrapping

Several CSS properties deal with these issues, but the specs are still in the works (at the “Working Draft” stage).

White Space

The white-space property lets you specify a combination of properties for which it serves as a shorthand: white-space-collapsing and text-wrap. Here’s a breakdown of what each property stands for:

  • normal
    white-space-collapsing: collapse/text-wrap: normal
  • pre
    white-space-collapsing: preserve/text-wrap: none
  • nowrap
    white-space-collapsing: collapse/text-wrap: none
  • pre-wrap
    white-space-collapsing: preserve/text-wrap: normal
  • pre-line
    white-space-collapsing: preserve-breaks/text-wrap: normal

This property can be useful if you want to, for example, display snippets of code on your website and preserve line breaks and spaces. Setting the container to white-space: pre will preserve the formatting.

Wordpress in The Future Of CSS Typography
WordPress uses white-space: nowrap on its dashboard so that the numbers indicating posts and comments don’t wrap if the table cell is too small.

Word Wrap

One property that is already well used is word-wrap. It supports one of two values: normal and break-word. If you set word-wrap to break-word and a word is so long that it would overflow the container, it is broken at a random point so that it wraps within the container.

International-gorilla in The Future Of CSS Typography
The International Gorilla Conservation Programme website uses word-wrap for its commenters’ names.

In theory, word-wrap: break-word should only be allowed when text-wrap is set to either normal or suppress (which suppresses line breaking). But in practice and for now, it works even when text-wrap is set to something else.

Bear in mind that according to the specification, the break-strict value for the word-break property is at risk of being dropped.

Word And Letter Spacing

Two other properties that are often used are word-spacing and letter-spacing. You can use them to control—you guessed it—the spacing between words and letters, respectively. Both properties support three different values that represent optimal, minimum and maximum spacing.

Show-and-tell in The Future Of CSS Typography
Show & Tell uses letter-spacing on its navigation links.

For word-spacing, setting only one value corresponds to the optimal spacing (and the other two are set to normal). When setting two values, the first one corresponds to the optimal and minimum spacing, and the second to the maximum. Finally, if you set all three values, they correspond to all three mentioned above. With no justification, optimal spacing is used.

It works slightly different for letter-spacing. One value only corresponds to all three values. The others work as they do for word-spacing.

The specifications contain a few requests for more information and examples on how white-space processing will work and how it can be used and be useful for languages such as Japanese, Chinese, Thai, Korean, etc. So, if you’d like help out, why not give it a read (it’s not that long), and see how you can contribute?

Indentation And Hanging Punctuation

Text indentation and hanging punctuation are two typographical features that are often forgotten on the Web. This is probably due to one of three factors:

  1. Setting them is not as straightforward as it could be;
  2. There has been a conscious decision not to apply them;
  3. Designers simply aren’t aware of them or don’t know how to properly use them.

Sushi-robots in The Future Of CSS Typography
The Sushi & Robots website has hanging punctuation on bulleted lists.

Mark Boulton has a good brief explanation of hanging punctuation in his “Five Simple Steps to Better Typography” series, and Richard Rutter mentions indentation on his website, The Elements of Typographic Style Applied to the Web. These are two very good reads for any Web designer.

So, the theory is that you should apply a small indentation to every text paragraph after the first one. You can easily do this with an adjacent sibling combinator:

p + p {
	text-indent: 1em;
}

This selector targets every paragraph (i.e. p) that follows another paragraph; so the first paragraph is not targeted.

Another typographic rule of thumb is that bulleted lists and quotes should be “hung.” This is so that the flow of the text is not disrupted by these visual distractions.

The CSS Text Level 3 specification has an (incomplete) reference to an upcoming hanging-punctuation property.

For now, though, you can use the text-indent property with negative margins to achieve the desired effect:

blockquote {
	text-indent: -0.2em;
}

For bulleted lists, just make sure that the position of the bullet is set to outside and that the container div is not set to overflow: hidden; otherwise, the bullets will not be visible.

Web Fonts And Font Decoration

font-face

Much talk has been made on the Web about font-face and whether it’s a good thing—especially after the appearance of Typekit (and the still-in-private-beta Fontdeck). The debate is mainly about how much visual clutter this could bring to Web designs. Some people (the argument goes) aren’t sufficiently font-savvy to be able to pull off a design in which they are free to use basically any font they wish. Wouldn’t our sensitive designer eyes be safer if only tested, approved Web-safe fonts were used?

On whatever side of the argument you fall, the truth is that the examples of websites that use font-face beautifully are numerous.

Snook in The Future Of CSS Typography
Jonathan Snook’s recently redesigned website uses the font-face property.

The font-face property is fairly straightforward to grasp and use. Upload the font you want to use to your website (make sure the licence permits it), give it a name and set the location of the file.

In its basic form, this is what the font-face property looks like:

@font-face {
	font-family: Museo Sans;
	src: local(“Museo Sans”), url(MuseoSans.ttf) format(“opentype”);
}

The two required font-face descriptors are font-family and src. In the first, you indicate how the font will be referenced throughout your CSS file. So, if you want to use the font for h2 headings, you could have:

h2 {
	font-family: Museo Sans, sans-serif;
}

With the second property (src), we are doing two things:

  1. If the font is already installed on the user’s system, then the CSS uses the local copy instead of downloading the specified font. We could have skipped this step, but using the local copy saves on bandwidth.
  2. If no local copy is available, then the CSS downloads the file linked to in the URI. We also indicate the format of the font, but we could have skipped that step, too.

For this property to work in IE, we would also need the EOT version of the font. Some font shops offer multiple font formats, including EOT, but in many cases we will need to convert the TrueType font using Microsoft’s own WEFT, or another tool such as ttf2eot.

Some good resources for finding great fonts that can be used with font-face are Font Squirrel and Fontspring.

text-shadow

The text-shadow property allows you to add a shadow to text easily and purely via CSS. The shadow is applied to both the text and text decoration if it is present. Also, if the text has text-outline applied to it, then the shadow is created from the outline rather than from the text.

Neutron in The Future Of CSS Typography
Neutron Creations website uses text-shadow.

With this property you can set the horizontal and vertical position of the shadow (relative to the text), the color of the shadow and the blur radius. Here is a complete text-shadow property:

p {
	text-shadow: #000000 1px 1px 1px;
}

Both the color and blur radius (the last value) are optional. You could also use an RGBa color for the shadow, making it transparent:

p {
	text-shadow: rgba(0, 0, 0, 0.5) 1px 1px 1px;
}

Here we define the R, G and B values of the color, plus an additional alpha transparency value (hence the a, whose value here is 0.5).

The specification still has some open questions about text-shadow, like how should the browser behave when the shadow of an element overlaps the text of an adjoining element? Also, be aware that multiple text shadows and the text-outline property may be dropped from the specification.

New Text-Decoration Properties

One problem with the text-underline property is that it gives us little control. The latest draft of the specification, however, suggests new and improved properties that may give us fine-grained control. You can’t use them yet, but we’ll give you a condensed sneak peek at what may come.

  • text-decoration-line
    Takes the same values as text-decoration: none, underline, overline and line-through.
  • text-decoration-color
    Specifies the color of the line of the previous property.
  • text-decoration-style
    Takes the values of solid, double, dotted, dashed and wave
  • text-decoration
    The shorthand for the three preceding properties. If you specify a value of only one of none, underline, overline or line-through, then the property will be backwards-compatible with CSS Level 1 and 2. But if you specify all three values, as in text-decoration: red dashed underline, then it is ignored in browsers that don’t support them.
  • text-decoration-skip
    Specifies whether the text decoration should skip certain types of elements. The proposed values are none, images, spaces, ink and all.
  • text-underline-position
    With this property, you can control, for example, whether the underline should cross the text’s descenders or not: auto, before-edge, alphabetic and after-edge.

Controlling Overflow

The text-overflow property lets you control what is shown when text overflows its container. For example, if you want all of the items in a list of news to have the same height, regardless of the amount of text, you can use CSS to add ellipses (…) to the overflow to indicate more text. This technique is commonly seen in iPhone apps and websites.

Nyt-app in The Future Of CSS Typography
The New York Times iPhone app uses an ellipsis for overflowing text.

This property works in the latest versions of Safari and Opera and in IE6 (where the overflowing element should have a set width, such as 100%) and IE7. To be able to apply the property to an element, the element has to have overflow set to something other than visible and white-space: nowrap. To make it work in Opera, you need to add the vendor-specific property:

li {
	white-space: nowrap;
	width: 100%;
	overflow: hidden;
	-o-text-overflow: ellipsis;
	text-overflow: ellipsis;
}

In the Editor’s draft of the specification, you can see that other properties related to text-overflow are being considered, such as text-overflow-mode and text-overflow-ellipsis, for which text-overflow would be the shorthand.

Alignment And Hyphenation

Controlling hyphenation online is tricky. Many factors need to be considered when setting automatic hyphenation, such as the fact that different rules apply to different languages. Take Portuguese, in which you can hyphenate a word only at the end of a syllable; for double consonants, the hyphen must be located right in the middle.

The specification is still being developed, but the proposed properties are:

  • hyphenate-dictionary;
  • hyphenate-before and hyphenate-after;
  • hyphenate-lines;
  • hyphenate-character.

Hyphenation in The Future Of CSS Typography
Proposed specification for hyphenation on the W3C website.

This is a good example of how the input of interested Web designers is vital. Thinking about and testing these properties before they are finalized has nothing to do with being “edgy” or with showing off. By proposing changes to the specification and illustrating our comments with examples, we are contributing to a better and stronger spec.

Another CSS3 property that hasn’t been implemented in most browsers (only IE supports it, and only partially) is text-align-last. If your text is set to justify, you can define how to align the last line of a paragraph or the line right before a forced break. This property takes the following values: start, end, left, right, center and justify.

Unicode Range And Language

Unicode Range

The unicode-range property lets you define the range of Unicode characters supported by a given font, rather than providing the complete range. This can be useful to restrict support for a wide variety of languages or mathematical symbols, and thus reduce bandwidth usage.

Imagine that you want to include some Japanese characters on your page. Using the font-face rule, you can have multiple declarations for the same font-family, each providing a different font file to download and a different Unicode range (or even overlapping ranges). The browser should only download the ranges needed to render that specific page.

To see examples of how unicode-range could work, head over to the spec’s draft page.

Language

Use the :lang pseudo-class to create language-sensitive typography. So, you could have one background color for text set in French (fr) and another for text set in German (de):

div:lang(fr) {
	background-color: blue;
}

div:lang(de) {
	background-color: yellow;
}

You might be wondering why we couldn’t simply use an attribute selector and have something like the following:

div[lang|=fr] {
	background-color: blue;
}

Here, we are targeting all div elements whose lang attribute is or starts with fr, followed by an -. But if we had elements inside that div, they wouldn’t be targeted by this selector because their lang attribute isn’t specified. By using the :lang pseudo-class, the lang attribute is inherited to all children of the elements (the whole body element could even be holding the attribute).

The good news is that all latest versions of the major browsers support this pseudo-class.

Conclusion

In surveying the examples in this article, you may be wondering why to bother with most of them.

True, the specification is far from being approved, and it could change over time, but now is the time for experimentation and to contribute to the final spec.

Try out these new properties, and think of how they could be improved or how you could implement them to make your life easier in future. Having examples of implementations is important to the process of adding a property to the spec and, moreover, of implementing it in browsers.

You can start with the simple step of subscribing to the CSS Working Group blog to keep up to date on the latest developments.

So, do your bit to improve the lot of future generations of Web designers… and your own!

Resources and Interesting Links

(al)


© Inayaili de Leon for Smashing Magazine, 2010. | Permalink | 56 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags:

Tags:

The Seven Deadly Sins Of JavaScript Implementation

Smashing-magazine-advertisement in The Seven Deadly Sins Of JavaScript Implementation
 in The Seven Deadly Sins Of JavaScript Implementation  in The Seven Deadly Sins Of JavaScript Implementation  in The Seven Deadly Sins Of JavaScript Implementation

Using JavaScript has become increasingly easy over the last few years. Whereas back in the day we needed to know the quirks of every browser, now many libraries such as jQuery, YUI, Dojo and MooTools allow someone who doesn’t even know JavaScript to spruce up boring HTML documents with impressive and shiny effects. By piggy-backing on the CSS selector engine, we have moved away from the complexity and inconsistencies of the DOM and made things much easier.

If you look at some of the code that has been released, though, we do seem to have taken a step backwards. In gaining easier access, we also became a bit sloppy with our code. Finding clearly structured, easy-to-maintain jQuery code is quite tough, which is why many plug-ins do the same thing. Writing one yourself is faster than trying to fathom what other developers have done.

The rules for solid, maintainable and secure JavaScript haven’t changed, though. So, let’s run through the seven sins of JavaScript development that will bite you in the backside when you have to maintain the code later on or hand it over to another party.

We’ve all had to work with code written by other people. We have despaired over the lack of maintainability and documentation as well as weird logic. Funny enough, as developers, we started to see this as normal and got used to ignoring other people’s work and instead writing new code for the same problems over and over, as if we were subconsciously trying to secure our jobs by leaving behind unmaintainable code—code that only we understood, while complaining that no good solutions were out there.

[Offtopic: By the way, did you know that Smashing Magazine has a mobile version? Try it out if you have an iPhone, Blackberry or another capable device.]

Sins Of Our Fathers: Browser-Specific Code

One of the main obstacles that kept us from evolving as developers was that JavaScript was largely browser-specific.

This was mainly because browsers did not support the standards (or were shipped before the governing bodies agreed on standards at all), and because we had to deliver our work before the competition and without extending the overly optimistic deadline set by our project managers.

This happens to be one reason why Internet Explorer 6 refuses to die. Hundreds of expensive software packages that are being used in offices worldwide were built when this browser was state of the art. This—and the monoculture that advocated using one software vendor for everything from the operating system to documents to spreadsheets to the browser—is the reason why companies now can’t simply discontinue support for it. It also means that newer versions of IE will always have to support the rendering mistakes of IE6 in one way or another. IE6 is the Frankenstein of the Internet, haunting its creators, terribly misunderstood by the townsfolk, who would sooner kill it, burn it and dance around it than make any sense of it.

The good news is that you won’t find many scripts these days that begin with if(document.all){} and continue with else if(document.layers){}. If you do find one, please send its creator a brief email encouraging them to move on or, better yet, to redirect their website to a better script that is actually being maintained.

Libraries to the Rescue

The job of JavaScript libraries such as jQuery, YUI, MooTools, Dojo and Glow is to make JavaScript development predictable and to relieve developers of the living hell that we call browser support. In other words, they fix random bugs in browsers and free us to adopt standards without worrying that certain browsers won’t recognize them.

For example, the DOM method getElementById(id) should be straightforward: find the element with the ID id and return it. But because some versions of IE and Opera also return elements that have the name attribute of id, jQuery solves the problem this way:

var elem;

elem = document.getElementById( match[2] );

if ( elem ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}

// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}

This is where libraries are awfully useful and is why JavaScript libraries are here to stay. Browsers will always do things wrong, and old browsers will not be upgraded by end users, either because of the aforementioned company regulations or because people simply don’t care to keep up with the times.

So, while the practice of building software for certain browsers is on the decline (at least for JavaScript—with CSS, we have a whole other headache ahead of us), we still have to be mindful of certain sins.

Sin #1: Not Playing Nice With Other Scripts

Here’s the first one, which we still see a lot of on the Web. Sadly, it is very common in demo code for APIs and Web services: global variables, functions and DOM-1 event handlers.

What do I mean by these? Consider the following:

  • Every script in the HTML document has the same rights as the others and can, if need be, overwrite what other scripts have done before.
  • If you define a variable or function name, and some other include uses the same name, the initial one will be overwritten.
  • The same applies to event handlers if you attach them the old-school onEvent way.

Say you have the script script_one.js:

x = 5;
function init(){
  alert('script one init');
  document.getElementsByTagName('h1')[0].onclick = function(){
    this.style.background = 'blue';
  }
}
alert('x is '+x);
window.onload = init;

And immediately after this one, you include another script, script_two.js:

  x = 10;
  function init(){
    alert('script two init');
    document.getElementsByTagName('h1')[0].onclick = function(){
      this.style.color = 'white';
    }
  }
  alert('x is '+x);
  window.onload = init;

If you open this document in a browser, you will find that x turns from 5 to 10 and that the first init() is never called. The script two init alert() does not come up, nor does the h1 get a blue background when you click it. Only the text turns to white, which renders it invisible.

The solution is not to use onEvent handlers, but rather the proper DOM level 2 event handlers (they don’t work in IE, but let’s not worry about that at the moment—remember, this is what libraries are for). Furthermore, wrap your functions in another with a more unique name to prevent them from overriding each other.

var scriptOne = function(){
  var x = 5;
  function init(){
    alert('script one init');
    document.getElementsByTagName('h1')[0].addEventListener(
      'click',
      function(e){
        var t = e.target;
        t.style.background = 'blue';
      },
      false
    );
  }
  alert('x inside is '+x);
  return {init:init};
}();
window.addEventListener('load',scriptOne.init,false);
alert('x outside is '+x);

var scriptTwo = function(){
  var x = 10;
  function init(){
    alert('script two init');
    document.getElementsByTagName('h1')[0].addEventListener(
      'click',
      function(e){
        var t = e.target;
        t.style.color = 'white';
      },
      false
    );
  }
  alert('x inside is '+x);
  return {init:init};
}();
window.addEventListener('load',scriptTwo.init,false);
alert('x outside is '+x);

If you run this in a browser (not Internet Explorer 6), everything will come up as you expect: x is first 5, then 10 on the inside, and the heading turns blue and white when you click it. Both init() functions are called, too.

You also get an error. Because x is not defined outside the functions, the alert('x outside is '+x); never works.

The reason is that by moving the x into the scriptOne and scriptTwo functions and adding the var keyword in front of them, we have made them a part of those functions but hid them from the outside world. This is called a closure and is explained in detail here. It is probably the most powerful feature of JavaScript.

Using closures and var keywords, you won’t have the problem of variables with similar names overriding each other. This also applies in jQuery: you should namespace your functions.

This can be tough to grasp, so let’s look at a simpler example:

var x = 4;
var f = 3;
var me = 'Chris';
function init(){}
function load(){}

All of these are global variables and functions now. Any other script having the same variables will override these.

You can nest them in an object to avoid this:

var longerAndMoreDistinct = {
  x : 4,
  f : 3,
  me : 'Chris',
  init : function(){},
  load : function(){}
}

That way, only the longerAndMoreDistinct is global. If you want to run this function, you now have to call longerAndMoreDistinct.init() instead of init(). You can reach me as longerAndMoreDistinct.me and so on.

I don’t like this because I have to switch from one notation to another. So, we can do the following:

var longerAndMoreDistinct = function(){
  var x = 4;
  var f = 3;
  var me = 'Chris';
  function init(){}
  function load(){}
}();

You define longerAndMoreDistinct as the outcome of a function without a name that gets immediately executed (this is the () on the last line). This now means that all of the variables and functions inside exist only in this world and cannot be accessed from outside at all. If you want to make them accessible from outside, you need to return them to the outside world:

var longerAndMoreDistinct = function(){
  var x = 4;
  var f = 3;
  var me = 'Chris';
  function load(){}
  return {
    init:function(){}
  }
}();

Now init() is available as longerAndMoreDistinct.init() again. This construct of wrapping things in an anonymous function and returning some of them is called the Module pattern, and it keeps your variables safe. Personally, I still hate the shift in syntax, so I came up with the revealing module pattern. Instead of returning the real function, all I do is return a pointer to it:

var longerAndMoreDistinct = function(){
  var x = 4;
  var f = 3;
  var me = 'Chris';
  function load(){}
  function init(){}
  return {
    init:init
  }
}();

This way, I can make things either available or not available simply by adding to the object that is returned.

If you don’t need to give anything to the world and just want to run some code and keep all of your variables and function names safe, you can dispense with the name of the function:

(function(){
  var x = 4;
  var f = 3;
  var me = 'Chris';
  function load(){}
  function init(){}
})();

Using var and wrapping code in this construct makes it inaccessible to the outside world, but still makes it execute.

You may find this to be complex stuff, but there is a good way to check your code. JSLint is a validator for JavaScript, much like the HTML or CSS validators, and it tells you all the things that might be wrong with your code.

Sin #2: Believing Instead Of Testing

The next big sin related to implementing JavaScript is expecting everything to go right: every parameter being in the right format, every HTML element you try to enhance being truly available, and every end user entering information in the right format. This will never be the case, and that last assumption is an especially bad one because it allows malicious users to inject dangerous code.

When you write JavaScript and give it to the world or integrate it in a product that will be maintained by a third party, a little paranoia is a good thing.

typeof is your friend. Regular expressions are your friend. indexOf(), split and length are your friends. In other words, do everything you can to make sure that incoming data is the right format.

You will get a lot of errors with native JavaScript; if you do anything wrong, you’ll know what happened. The annoying thing about most JavaScript libraries is that when they fail to execute some functionality, they do it silently. The maintainer is left guessing and has to run through all the code and start debugging with stop points (or—shudder!—alerts()) to reverse-engineer where you entered instable code. To avoid this, simply wrap whatever you can in a test case rather than try to access it.

Sin #3: Using The Wrong Technology For The Job

The biggest problem with JavaScript happens when you use the wrong tool for the job. It makes maintenance a nightmare and deteriorates the code’s quality. Use tools for the jobs they were meant for. This means:

  • Absolutely essential content and mark-up should be in HTML, regardless of the environment it will be displayed in.
  • Any “look and feel” elements should be maintainable through CSS. You should not have to scour through JavaScript to change a color.
  • Any interaction with the user that goes beyond hover effects (which, by definition, are an invitation to interact and not the interaction itself—because they are inaccessible to keyboard users) should be done with JavaScript.

The main reason why this is still a valid, pragmatic and sensible approach to development is that as Web technologies get muddled (for example, you can create content with CSS and JavaScript, animate and transform in CSS and—if you really want—paint with HTML), people’s skills and interests in these different technologies vary quite a bit.

Semantic mark-up buffs are not much interested in applying closures in JavaScript. JavaScript developers are not much interested in the order of elements in CSS. And CSS fans aren’t keen to learn how to make a JavaScript animation run flicker-free.

This results in the same problems being solved over and over again, only with different technologies. This is a market-wide problem: a lot of state-of-the-art Canvas tricks were done in Flash years ago, their impact debated and their problems fixed.

My favorite instance of this is when people write loops to hide a lot of elements on the page to make them available later on.

Say this is your HTML:

<h2>Section 1</h2>
<div class="section">
  <p>Section 1 content</p>
</div>

<h2>Section 2</h2>
<div class="section">
  <p>Section 2 content</p>
</div>

<h2>Section 3</h2>
<div class="section">
  <p>Section 3 content</p>
</div>

<h2>Section 4</h2>
<div class="section">
  <p>Section 4 content</p>
</div>

The normal jQuery solution for this would be:

$(document).ready(function(){
  $('.section').hide();
  $('h2').click(function(e){
    $(this).next().toggle();
  })
});

And then you realize that making the style of the current section deviate from that of the other sections would be great.

$(document).ready(function(){
  $('.section').hide();
  $('h2').click(function(e){
    $(this).next().toggle();
    $(this).next().css('background','#ccc');
    $(this).next().css('border','1px solid #999');
    $(this).next().css('padding','5px');
  })
});

A few things are wrong with this. For starters, you’ve made it hard to maintain this by controlling the look and feel in JavaScript, not CSS (more on this later). Secondly, performance: while jQuery is amazingly speedy, a lot of code is still hidden under the hood in $('.section').hide(). The last, and very painful, performance issue is the copied and pasted lines that set the CSS. Don’t ask jQuery to find the next sibling four times and do something to it. You could store the next() in a variable, but even that is not needed if you chain. If you really need to set a lot of CSS in jQuery, use a map:

$(document).ready(function(){
  $('.section').hide();
  $('h2').click(function(e){
    $(this).next().toggle().css({
      'background':'#ffc',
      'border':'1px solid #999',
      'padding':'5px'
    });
  })
});

What if you then want to allow only one of them to be open at any time? Inexperienced developers would do something like this:

$(document).ready(function(){
  $('.section').hide();
  $('h2').click(function(e){
    $('.section').hide();
    $(this).next().toggle().css({
      'background':'#ffc',
      'border':'1px solid #999',
      'padding':'5px'
    });
  })
});

This does the job, but you’re looping around the document and accessing the DOM a lot, which is slow. You can alleviate this by keeping the current open section in a variable:

$(document).ready(function(){
  var current = false;
  $('.section').hide();
  $('h2').click(function(e){
    if(current){
      current.hide();
    }
    current = $(this).next();
    current.toggle().css({
      'background':'#ffc',
      'border':'1px solid #999',
      'padding':'5px'
    });
  })
});

Predefine the current section as false, and set it when you click the first heading. You would then hide current only if it is true, thereby removing the need for another loop through all elements that have the class section.

But here is the interesting thing: if all you want is to show and hide sections, you don’t need any looping at all! CSS already goes through the document when it renders and applies classes. You just need to give the CSS engine something to hang on to, such as a class for the body:

$(document).ready(function(){
  $('body').addClass('js');
  var current = null;
  $('h2').click(function(e){
    if(current){
      current.removeClass('current');
    }
    current = $(this).next().addClass('current');
  })
});

By adding the class js to the body of the document and toggling the class current for the current section, you maintain control of the look and feel in CSS:

<style type="text/css" media="screen">
  .section{
    border:1px solid #999;
    background:#ccc;
  }
  .js .section{
    display:none;
  }
  .js .current{
    display:block;
    border:1px solid #999;
    background:#ffc;
  }
</style>

The beauty of this is that the handle will be re-usable by the CSS designer and maintainer. Anything without the .js selector would be the non-scripting-enabled version of a part of the document, and anything with the .js selector is applied only when JavaScript is available. And yes, you should think about the case when it is not.

Sin #4: Depending On JavaScript And Certain Input Devices

There is quite a discussion about the need to consider non-JavaScript environments in this day and age, but here is a fact: JavaScript can be turned off, and any JavaScript could break the page for the other scripts that are included. Given the flakiness of code out there that may be running alongside yours and the instability of wireless and mobile connections, I for one want to build one thing: code that works.

So, making sure that the most basic usage of your product does not depend on JavaScript is not just nice to have but essential if you expect people to actually use the product.

Absolutely nothing is wrong with using JavaScript heavily. On the contrary, it makes the Web much smoother and saves us a lot of time if done right. But you should never promise functionality that doesn’t work. And if you rely on JavaScript, this is exactly what you’re doing. I’ve already covered the effects of bad JavaScript in detail in the AJAX, JavaScript testing and security articles here on Smashing Magazine, but once again here are some simple steps you can take to make sure you don’t break your promise to end users:

  • Anything vital to the functionality of your product should not require JavaScript. Forms, links and server-side validation and re-direct scripts are your friends.
  • If something depends on JavaScript, build it with JavaScript and add it to the document using the DOM or the equivalent method in your library of choice.
  • If you add JavaScript functionality, make sure it works with the keyboard and mouse. Click and submit handlers are bullet-proof, whereas key and mouse events are flaky and don’t work on mobile devices.
  • By writing clever back-end code that recognizes when data is required by JavaScript rather than building APIs that render HTML, you avoid having to do double-maintenance, which is an argument that many of the “Everyone enables JavaScript” zealots bring up a lot. For proof of this, check out the presentation on building Web applications using YQL and YUI that I gave a few weeks ago (video in English and German).

When JavaScript Dependence Is Okay (to a Degree)

A lot of misunderstanding about JavaScript dependence stems from people making blanket statements based on the environments they work in.

If you are a Google engineer working on Gmail, you would be hard pressed to think of why you would even bother working without JavaScript. The same goes for widget developers who work on OpenSocial widgets, mobile applications, Apple widgets and Adobe Air. In other words, if your environment already depends on JavaScript, then by all means don’t bother with a fall-back.

But do not take these closed environments and edge-case applications as the standard by which we should be measuring JavaScript. JavaScript’s greatest power and greatest problem is its versatility. Saying that all websites can stand JavaScript because Gmail needs it is like saying that all cars should have a start button because they work great in Hybrids, or that hybrid cars should have massive tanks and cow catchers because they work great on Hummers. The technical feature set of a product depends on its implementation and target market. Different applications have different base functionality that needs to be satisfied in order to reach the largest audience and not block people out.

Consider the Use Cases and Maintenance

One fascinating aspect of JavaScript-dependent code is that, in many cases, people have simply not considered all the use cases (here’s a great example). Take the following HTML:

<form action="#" id="f">
  <div>
    <label for="search">Search</label>
    <input type="text" value="kittens" id="search">
    <input type="submit" id="s" value="go">
  </div>
</form>
<div id="results"></div>

Without JavaScript, this does nothing whatsoever. There is no sensible action attribute, and the text field has no name attribute. So, even when you send the form off, the server won’t get the information that the user has entered.

Using jQuery and a JSON data source such as YQL, you can do a pure JavaScript search with this:

$('#s').click(function(event){
  event.preventDefault();
  $('<ul/>').appendTo('#results');
  var url =
  $.getJSON('http://query.yahooapis.com/v1/public/yql?'+
            'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'+
            'from%20search.web%20where%20query%3D%22'+
            $('#search').val() + '%22&format=json&'+
            'callback=?',
    function(data){
      $.each(data.query.results.result,
        function(i,item){
          $('<li><h3><a href="'+item.clickurl+'">'+
             item.title+' ('+item.dispurl+')</a></h3><p>'+
             (item.abstract || '') +'</p></li>').
            appendTo("#results ul");
        });
    });
});

This works… unless of course you are like me and prefer to send forms by hitting “Enter” rather than clicking the “Submit” button. Unless I tab through the whole form and focus on the “Submit” button, I get nothing.

So, that’s the first thing to fix. If you create forms, never use a click handler on the button. Instead, use the submit event of the form. This catches both the clicking “Submit” and hitting “Enter” cases. With one change, you now support all of the keyboard users out there, and the whole change is contained in the first line:

$('#f').submit(function(event){
  event.preventDefault();
  $('<ul/>').appendTo('#results');
  var url =
  $.getJSON('http://query.yahooapis.com/v1/public/yql?'+
            'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'+
            'from%20search.web%20where%20query%3D%22'+
            $('#search').val() + '%22&format=json&'+
            'callback=?',
    function(data){
      $.each(data.query.results.result,
        function(i,item){
          $('<li><h3><a href="'+item.clickurl+'">'+
             item.title+' ('+item.dispurl+')</a></h3><p>'+
             (item.abstract || '') +'</p></li>').
            appendTo("#results ul");
        });
    });
});

We’ve now covered the first case. But without JavaScript, the form still doesn’t do anything. And another problem brings us to the next sin of writing JavaScript.

Sin #5: Making Maintenance Unnecessarily Hard

One thing that keeps great code off the Web is that our work environment, deadlines and hiring practices condition developers to build code for quick release, without considering how difficult maintaining that code will be later on. I once called JavaScript the village bicycle of Web design (slides here): anyone can go for a ride. Because the code is available in the open, future maintainers will be able to mess around with it and extend it any way they like.

The sad thing is that the harder your code is to maintain, the more errors will be added to it, leading it to look more like alphabet soup than organized script.

Take the above example. Those of you who haven’t worked with YQL and JSON-P for cross-domain AJAX undoubtedly had a “What?” moment looking at the code. Furthermore, keeping a lot of HTML in JavaScript easy to follow is hard, and guess what is the first thing to change when a new design for the page comes along? Exactly: the HTML and CSS. So, to make it easier to maintain, I for one would shift all of the work to the back end, thus making the form work without JavaScript and keeping maintenance of all the HTML in the same document:

<?php
if(isset($_GET['search'])){
  $search = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
  $data = getdata($search);
  if($data->query->results){

    $out = '<ul>';

    foreach($data->query->results->result as $r){

      $out .= "<li>
                 <h3>
                   <a href=\"{$r->clickurl}\">{$r->title}
                     <span>({$r->dispurl})</span>
                   </a>
                 </h3>
                 <p>{$r->abstract}</p>
               </li>";
    }

    $out .= '</ul>';

  } else {

    $out = '<h3>Error: could not find any results</h3>';

  }
}

if($_SERVER['HTTP_X_REQUESTED_WITH']!=''){
  echo $out;
  die();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Ajax Search with PHP API</title>
  <link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
  <form action="independent.php" id="f">
    <div>
      <label for="search">Search</label>
      <input type="text" value="kittens" name="search" id="search">
      <input type="submit" id="s" value="Go">
    </div>
  </form>
  <div id="results"><?php if($out!=''){echo $out;}?></div>
  <script src="jquery.js"></script>
  <script src="ajaxform.js"></script>
</body>
</html>
<?php
function getdata($search){
  $url = 'http://query.yahooapis.com/v1/public/yql?'.
         'q=select%20abstract%2Cclickurl%2Cdispurl%2Ctitle%20'.
         'from%20search.web%20where%20query%3D%22'.$search.'%22'.
         '&format=json';
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $output = curl_exec($ch);
  curl_close($ch);
  $data = json_decode($output);
  return $data;
}
?>

Someone who doesn’t understand PHP at all should still be able to change the HTML display without breaking the code. With this in place, the JavaScript boils down to a very simple script:

$('#f').submit(function(event){
  event.preventDefault();
  $.get('independent.php?search=' + $('#search').val(),
    function(data) {
      $('#results').html(data);
    }
  );
});

The normal way to make code more maintainable is to move everything that is likely to change away from the main functional part of the script into a configuration object at the very top of the script. You can return this as an object to the outside world to allow people to set it before they initialize the main functionality.

So, one change we can make to our earlier example—albeit a small one now, but that can change quickly when more requirements come in—is to have a configuration section right up front that defines the CSS classes in use:

$(document).ready(function(){
  /* Configuration object - change classes, IDs and string here */
  var config = {
  /* CSS classes that get applied dynamically */
    javascriptenabled:'js',
    currentsection:'current'
  }

  /* functionality starts here */
  $('body').addClass(config.javascriptenabled);
  var current = null;
  $('h2').click(function(e){
    if(current){
      current.removeClass(config.currentsection);
    }
    current = $(this).next().addClass(config.currentsection);
  })
});

For more information on configuration objects and why they rock for maintenance, check out the blog post “Providing Script Configuration Inline and Programatically“.

In summary, go over your code once more when you think you’ve finished with it and the next person is about to take it over.

Sin #6: Not Documenting Your Code

“Good code documents itself” is a terribly common and misguided belief. In my years as a developer, I’ve found that my style of coding has changed constantly. What was common knowledge and best practice in 2004 might be forgotten or even considered poor style these days.

Documenting all of the tricks and workarounds we do to make our code work in different browsers is definitely a good idea. This allows future maintainers to remove them when the targeted browser version becomes obsolete or a library function fixes the issue.

Commenting your code also allows the maintainer to trace it back to you should they need some piece of information, and it allows people who have stumbled across your script to include it in a larger solution or library (which has happened to me). Because JavaScripts tend replicate on the Web (in all of those blogs and “script collections”), it is also a way to make your name known.

Don’t go overboard with commenting, though. Obvious things don’t need to be spelled out. I have found the following situations worthy of comment:

  • Necessary hacks
    Browser hacks; content clean-up; things that should be supported server-side but are not yet.
  • Sections that are likely to change
    Timely solutions; IDs, classes and strings (as explained earlier).
  • Start of classes and reusable functions
    With name, author, version, date and license.
  • Third-party code
    Give credit where credit is due.
  • Sections with dependencies
    Some comment like, “Needs the Google API with an own key—this one will not work on your server.”

In short, comment on anything that deviates from the normal flow of coding. I tend to use /* */ instead of // because it won’t create a bug if people remove the line break by accident.

Special Case: Commenting Out Code

One special case is commenting out sections that will be necessary in future releases or that depend on functionality not currently available. This can be amazingly useful but also a security risk, depending on what you’re commenting out. For example, don’t leave in any code that points to server-side APIs that are not available yet but could at any time be half-implemented. I’ve seen this before, where administrator links with the full unprotected path were commented out in the HTML.

Still, commenting out can be very useful for debugging. One neat trick is the following:

/*

myFunction('do something');

// */

This is now commented out. But by adding a single slash in front of the first comment line, you will uncomment the whole block and make it live.

//*

myFunction('do something');

// */

This trick makes it awfully easy to toggle whole blocks.

Sin #7: Optimizing For Machines, Not People

The last sin is over-optimizing JavaScript based on the scads of information about performance that are available to us. You will find a lot of information on the Web about optimizing JavaScript for performance in the current browser environment. Notice that “current browser environment”—much information is browser- and version-specific and a necessary evil for now, but not necessarily in future. If your application is large or your website is high traffic, knowing and applying this information could make or break it. Again, though, a lot of this applies to edge cases that would have little impact on small projects and environments. This optimization does make it harder to maintain the code; some of the things we need to do to make browsers run fast on high-scale websites, such as writing out script nodes with document.write(), are downright nasty.

When faced with the choice between making code cleaner and easier to amend, extend and understand on the one hand, and shaving two milliseconds off every page load on the other, I opt for the former. A lot of JavaScript optimization can be done through scripts. And rather than teach all developers on a project the ins and outs of JavaScript performance, an expert team (or even a tool) could optimize the code before it goes live.

If you can do anything with machines to make the jobs of other machines easier, do it. The time has come for us to apply build processes as much to front-end code as we do to back-end code, instead of forcing ourselves to follow coding practices that go against the natural flow of writing code.

Further Reading

I hope you’ve gotten an idea now of how to make scripts more useful, easier to extend and safer to use. For more information, please check out the following links:

(al)


© Christian Heilmann for Smashing Magazine, 2010. | Permalink | 68 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags:

Tags:

Free Dark and Clean WordPress Theme: Designpile

Smashing-magazine-advertisement in Free Dark and Clean WordPress Theme: Designpile
 in Free Dark and Clean WordPress Theme: Designpile  in Free Dark and Clean WordPress Theme: Designpile  in Free Dark and Clean WordPress Theme: Designpile

In this post we are glad to release DesignPile WordPress Theme, a theme designed by Site 5 and released for Smashing Magazine and its readers. The theme comes with 3 color styles and a couple of jQuery-based goodies. It can be used for portfolios and blogs as well as corporate webAs usual, the theme is free to use in private and commerical projects.

Release in Free Dark and Clean WordPress Theme: Designpile

Download the theme for free!

The theme is released under GPL. You can use it for all your projects for free and without any restrictions. Please link to this article if you want to spread the word. You may modify the theme as you wish.

Designpile-main in Free Dark and Clean WordPress Theme: Designpile

Features

Here are some of the features of the theme:

  • Widget ready (footer and sidebar),
  • Easy to setup, the Theme Options Page has 3 color styles,
  • Custom homepage,
  • Simple Post Thumbnails Plugin,
  • 125×125 ads section with enable/disable option, using “WP125″ plugin,
  • JQuery Lightbox,
  • JQuery Forms,
  • AJAX-based based contact form,
  • Live form email validation,
  • Theme Requirements: Wordpress 2.9.1+

Sidebar in Free Dark and Clean WordPress Theme: Designpile
Sidebar

Content in Free Dark and Clean WordPress Theme: Designpile
Content, overview

About in Free Dark and Clean WordPress Theme: Designpile
“About the author”-section

Comments in Free Dark and Clean WordPress Theme: Designpile
Comments

Categories in Free Dark and Clean WordPress Theme: Designpile
Categories archive section

Thank you, Gabi Schiopu and the Site 5 design team! We appreciate your work and your good intentions!


© Smashing Editorial for Smashing Magazine, 2010. | Permalink | 81 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags:

Tags:

50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Smashing-magazine-advertisement in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)
 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)  in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)  in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Although CSS is generally considered a simple and straightforward language, sometimes it requires creativity, skill and a bit of experimentation. The good news is that designers and developers worldwide often face similar problems and choose to share their insights and workarounds with the wider community.

This is where we come in. We are always looking to collect such articles for our posts so that we can deliver the most useful and relevant content to our readers. In this post, we present an overview of useful CSS/jQuery coding tips, tricks and techniques for visual effects, layouts and web form design to help you find solutions to the problems you are dealing with or will have to deal with in future.

You may want to look at similar CSS-related posts that we published last months:

[Offtopic: by the way, did you already get your copy of the brand new Smashing Book?]

CSS Layouts: Techniques And Workarounds

Facebook Style Footer Admin Panel
Learn how to re-create the Facebook footer admin panel with CSS and jQuery. Also check out part 2.

Css-technique-15 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Adaptable View: How Do They Do It?
This tutorial explains how to manually change a layout, and it shows two great examples and “how they did it.”

Css-technique-01 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Easy Display Switch with CSS and jQuery
A quick and simple way to enable users to switch page layouts using CSS and jQuery.

Css-198 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Quick Tip – Resizing Images Based On Browser Window Size
In fluid layouts, formatting text to adjust smoothly to window size is easy, but images are not as fluid-friendly. This quick tip shows how to switch between two image sizes based on the size of the browser, the DIV or whatever else you choose.

Css-064 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

One Page Résumé Site
A clean layout on one page—literally (just one index.html file with optional images). It comes with contact information in microformats and a main area for the resume using a definition list (dl). And it prints well.

Css-000 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Pegs: Automate Display: fixed++
Chris Wetherell posts on Pegs, a strategy for having one scroll bar but independent scrolling areas. After the first one, click on the other items to flip between sizes. You will see that an area’s scroll depends on the configuration.

Css-135 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

CSS 100% Height
A common problem among designers is how to get a div to stretch 100% of the window’s height. There are a few different techniques out there, and this tutorial shows one of them.

Css-technique-18 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

CSS3 Drop-Down Menu
A clean, simple a nice navigation menu, designed by Nick La.

Css-technique-21 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

CSS Trick for a Scrolling Transparent Background Effect
Scroll the page to watch a battle between good and evil take shape. The effect requires two images: one transparent and one tiled gradient image. The gradient scrolls under the transparent PNG. Because it matches the colors in the PNG, each set of images disappears, depending on the part of the gradient they’re on top of.

Css-148 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Fluid Images
By default, an image element that is 500 pixels doesn’t exactly play nice with a container as large as 800 pixels or one as small as 100. What’s a designer to do?

Css-069 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Scroll/Follow Sidebar, Multiple Techniques
A really simple concept: the sidebar follows you as you scroll down the page. There are a number of ways to go about it. Two are covered here: CSS and JavaScript (jQuery), with a bonus CSS trick.

Css-technique-00 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Vertical Centering With CSS
There are a few different ways to vertically center objects using CSS, but choosing the right one can be difficult. Here is a list of the best ways and an explanation of how to create a nice centered website.

Css3-new-08 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Create YouTube-like adaptable view using CSS and jQuery
Other than the “Turn off the lights” feature, YouTube has great stuff, such as the “change view” feature, which allows you to switch between normal and wide mode, thus expanding or shrinking the video area. Creating this is very simple.

Css-142 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

How To Create a Horizontally Scrolling Site
If websites were made of wood, the grain would run up and down. Vertical is the natural flow of the Web. But browsers are equipped with vertical and horizontal scroll bars, right? We have the choice to go against the grain and create web pages that scroll primarily horizontally and that even expand horizontally to accommodate more content. Perhaps a slight blow to usability, but a cool creative touch nonetheless!

Css-technique-02 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Purely CSS – Faking Minimum Margins
min-margin is non-existent in the CSS world. After you’ve pondered and Googled it, check out the solution here.

Css-technique-03 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Create Sidebars of Equal Height with Faux Columns
CSS can be tricky business. Creating columns of equal height, where the content in one column is longer than the content in another, is frustrating. Here’s where the faux-column technique can help. Find out how this solution makes even the most complicated layout a breeze to code.

Setting Equal Heights with jQuery
Here is a script to match the heights of boxes in the same container and create a tidy grid, with little overhead.

Css-141 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Quick Tip: Centered Fake Floats
There were ways to center-align left-floated elements, but then inline-block became popular and everything changed. After a bit of tinkering, Zaharenia Atzitzikaki found an efficient and (mostly) cross-browser-compatible way to center elements without floats.

6 Flexible jQuery Plugins to Control Web Page Layouts Easily
A collection of six jQuery plug-ins to manage page layouts easily.

Css-125 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Four Methods to Create Equal-Height Columns
This article discusses ways to create equal-height columns that work in all major browsers (including IE6). All of the methods show how to create a three-column layout.

Css-065 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

How to: CSS Large Background
A tutorial with various CSS examples for how to create a large background using either a single image or double images.

Css-080 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

A Nice Little CSS Positioning Technique
Here, we have a basic unordered list (ul), with left-floated images where the text doesn’t wrap under the images. Of course, this technique could be deployed in loads of other instances.

Css-117 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Perfect Full Page Background Image
This technique allows an image to fill the page, with no white space. The image scales as needed and retains its proportions, without triggering scroll bars.

Css-162 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Smart Columns With CSS and jQuery
In observing liquid-width websites, Soh Tanaka sees two common techniques for displaying columns: fixed columns and liquid columns. He points out the drawbacks of both and pitches his solution.

Css-057 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Images And Visual Effects With CSS

A Beautiful Apple-Style Slideshow Gallery With CSS and jQuery
Create an Apple-like slideshow gallery, similar to the one used on Apple’s website to showcase products. It works entirely in the front end; no PHP or databases required.

Css-technique-12 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Rolling a coke can around with pure CSS
Román Cortés is having a lot of fun doing CSS tricks these days. He just built a rolling coke can that uses background-attachment, background-position and a few other tricks to achieve the effect. No fancy CSS3 needed here!

Css3-new-10 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Grayscale Hover Effect With CSS and jQuery
A few months ago, James Padolsey introduced a cool grayscale technique for non-IE browsers. His technique inspired Soh Tanaka to come up with a workaround with a similar effect. His solution relies on CSS Sprites and a few lines of jQuery, but it requires a bit of preparation before implementation. It is not recommended for large-scale projects; it is probably best for portfolio pieces.

Css-055 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Codename Rainbows
Some JavaScript and CSS magic is used here to apply a two-color gradient to text. Shadows and highlights can also be applied. This works especially well on big websites and for dynamic content where creating images for every instance would be impractical.

Css-097 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

3 Easy and Fast CSS Techniques for Faux Image Cropping
This article summarizes three fast and easy CSS techniques for displaying only a portion of an image. All of the techniques need only a couple of lines of CSS. You are not literally cropping, which is why it’s called faux image cropping. These techniques can be helpful if you want to keep images to a certain size (for example, thumbnails in a news section). Being able to use CSS to control which portion of an image to display is great.

Css-technique-08 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Image Rollover Borders That Do Not Change Layout
With CSS, the border of any block-level element is factored into the element’s size in the layout. So, if you add a border to an element on hover, the layout will shift. In this post, you will find how to use the regular border property and create inner borders to get around that.

Css-technique-10 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Horizontal Stripes
This tutorial shows you how to create never ending horizontal stripes in your web design using CSS.

Css-technique-14 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Nine Techniques for CSS Image Replacement
Put nine different techniques of image replacement to the test.

Css-technique-13 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Bokeh effects with CSS3 and jQuery
This tutorial teaches you how to re-create the bokeh effect with CSS 3. With some help from jQuery, we can add some randomness in colour, size and position for the effect.

Css-technique-16 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

A Stationary Logo That Changes on Page Scroll with CSS
Here is an interesting effect that modifies the logo when the page is scrolled, using the CSS background-attachment property.

Css3-new-04 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Silhouette Fade-Ins
To achieve the effect in the image above, first we need a DIV with the silhouettes as a background image. Then we put four images in that DIV, all the exact same size, with each band member highlighted. These images are hidden by default. Then you absolutely position four regions on top of the DIV; these are the roll-over link areas. With jQuery, we apply hover events to them, fading in the appropriate image.

Css-046 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Creating Triangles in CSS
Few people realize that a browser draws borders at angles. This technique takes advantage of that. One side of the border is given the color of the arrow, and the rest are transparent. Then you give the border a large width; the ones above are 20 pixels.

Css-004 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

A parallax optical illusion with CSS: The Horse in Motion
Time for some fun with CSS and optical illusions.

Css-203 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Pure CSS Line Graph
The idea here is not only to offer data visualization to people who aren’t comfortable using scripting languages, but to demonstrate the power of CSS and offer a different way of using CSS. If you are not a fan of line graphs and data visualization, you may still benefit from this article. Think of it as a CSS experiment, and learn a thing or two about CSS Sprites and positioning.

Css-037 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Zooming with jQuery and CSS
This post is about text zooming with jQuery and CSS. This is a basic-level tutorial about changing a style using a jQuery script. A simple way to zoom website content.

Css-146 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Create Resizing Thumbnails Using Overflow Property
This tutorial teaches you how to control thumbnail sizes. Sometimes we don’t have enough space to fit large thumbnails, and yet we would rather avoid small indecipherable images. Using this trick, we can limit the default dimensions of thumbnails and show them at full size when the user mouses over them.

Css-150 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Cross-browser drop shadows using pure CSS
Most methods of adding drop-shadows to content blocks require additional HTML mark-up and one or more PNG images. But by combining the Glow and Shadow filters, something that fairly closely resembles the rendered CSS3 shadow can be achieved.

Css-151 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Date Badges and Comment Bubbles for Your Blog
One of the things you have to deal with when your blog grows is having to cram more info into less space to show everything you want to show. One thing you can do is add an icon for the date and then a bubble over it with the number of comments for that post.

Css-technique-11 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

CSS Tables And Web Forms

UX trick: display form data as tabular data
This is a little trick to enhance the user experience of forms. It displays editable form data as readable tabular data.

Css-technique-04 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Tables: Not As Evil As You Think
Tables are evil, right? Yes and no. For tabular data, they’re not, of course. That’s what tables are for in the first place. CSS can do an excellent job of styling a properly formatted table, and the table structure provides good scaffolding for JavaScript calls. But what is addressed here is using tables for non-tabular data (i.e. for the layout). Yes, that’s right: using tables for layout.

Css-075 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Perfect Drop-Down Log-In Box Like Twitter Using jQuery
This shows you how to create a Twitter-style drop-down log-in form using jQuery. It’s really easy, it saves space on the page and visitors feel comfortable with the awesome toggle form.

Css-158 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Make a Select’s Options Printable
When printing a Web page with select elements on it, the select drop-down prints just as it looks on the Web. This of course is practically useless on the printed page. One option for handling this is to follow every select HTML element with an unordered list that duplicates the content. Hide the unordered list in your main CSS file and reveal it with your print style sheet. This is a reasonable approach, except that it’s a big ol’ pain in the butt to deal with all the time. Let’s rely on jQuery to do the heavy lifting instead.

Css-018 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Twitter-Like Log-In With jQuery and CSS
This post explains how to get the Twitter-like hide and show effect for logging in using jQuery and CSS.” Very simple: just five lines of JavaScript for the hide() and show() events and a little CSS.

Css-145 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Clean and Pure CSS Form Design
This tutorial illustrates how to design a pure CSS form without using HTML tables.

Css-105 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

CSSG Collection: Free Comment Styles
This is the second CSSG collection from CSS Globe.

Css-034 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Have a Field Day with HTML5 Forms
Here is a look at how to style a beautiful HTML5 form using some advanced CSS and the latest CSS3 techniques. You will definitely want to re-style your forms after having read this article.

Css-011 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Editable/Printable Invoice
Create editable and printable invoices using CSS and some JavaScript. This is version 2 from Vinh Pham.

Css-047 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

How to Mask Passwords Like the iPhone
Many smartphones, including the iPhone, show the last character that you typed in a password field with a delay of a second or two. You can see that last character but not the entire password. But browsers don’t do what these mobile devices do. Here is a solution, with some fancy JavaScript and behind-the-scenes trickery.

Css-074 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Make Web Forms Suck Less With Labels
We’ve been filling out Web forms for years, and we all gripe that they could be better. Even with generous padding, the fields are too small. But hardly anyone has improved the most under-rated interaction of them all: checkboxes and radio buttons.

Css-technique-20 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

FancyForm: JavaScript checkbox replacement
FancyForm is a powerful and flexible checkbox-replacement script that changes the appearance and function of HTML form elements. It is accessible and easy to use, and it degrades gracefully on older non-supported browsers.

Css-103 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

jQuery checkbox v.1.3.0 Beta 1
A lightweight custom-styled checkbox implementation for jQuery 1.2.x and 1.3.x.

Css-104 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Disabled labels and the Trilemma plug-in
The form above on the left makes use of the disabled attribute, but the default browser settings for disabled inputs don’t contrast as much as one would like. To better distinguish at a glance between which inputs are disabled and enabled, the labels of disabled inputs in the form on the right are styled with a faint gray color.

Css-127 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Fluid Search Box
Creating a fluid search box when you have only a single element next to it is trivial. What you should do is wrap the input in an element and use padding to create space for the fixed element; then position the fixed element absolutely (or relatively) in the space created by the padding.

Last Click

Browser Pong
A whole new pong game using three browser windows for the ball and racquets. Clever!

Css-180 in 50 Useful Coding Techniques (CSS Layouts, Visual Effects and Forms)

Related posts

You may want to look at similar CSS-related posts that we published last months:

(kk) (jb) (vf) (al)


© Smashing Editorial for Smashing Magazine, 2010. | Permalink | 48 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: ,

Tags:

Developing Sites With AJAX: Design Challenges and Common Issues

Smashing-magazine-advertisement in Developing Sites With AJAX: Design Challenges and Common Issues
 in Developing Sites With AJAX: Design Challenges and Common Issues  in Developing Sites With AJAX: Design Challenges and Common Issues  in Developing Sites With AJAX: Design Challenges and Common Issues

Almost every movie has a scene in which a character pull the protagonist aside and says, “There’s something you should know about [insert another character's name here].” Most of the time, we find out some dark secret about a supposed friend of the protagonist or that the main ally is actually an evil overlord. This is that moment, and I am here to tell you a few things about our friend in the Web 2.0 world: AJAX.

We seem to have AJAX licked. The Web technology is ubiquitous, and libraries and frameworks make it dead easy for us to create highly interactive Web applications and to spice up our static pages and blogs.

For example, we could take the following HTML…

<div id="target"></div>
<p><a href="#" class="ajaxtrigger">Let there be AJAX magic</a></p>

… and add this jQuery code:

$('.ajaxtrigger').click(function(){
  $('#target').load('ajaxcontent.html');
});

In a browser, if we clicked on the link labelled “Let there be AJAX magic,” the content of the HTML document ajaxcontent.html would be loaded and written into the element with the ID target. You can try this very simple AJAX example here. It’s simple and easy to use, but what’s really happening there? What is AJAX?

[Offtopic: by the way, do you know the Smashing Network has its own Smashing Network RSS Feed? Only excerpts are displayed in the feed.]

What Is AJAX?

After the main HTML document has loaded, AJAX loads content from the server and replaces parts of the document with that content rather than reload the main document. It’s as simple as that. AJAX stands for “Asynchronous JavaScript and XML” and was meant to load only XML documents, but we soon used it to load everything under the sun, and so the XML part was quickly forgotten. The asynchronous part is the killer feature; but what is it?

Ajax in Developing Sites With AJAX: Design Challenges and Common Issues
The traditional model for web applications (left) compared to the Ajax model (right).

Let’s start by analysing how a normal Web interaction works:

  1. The user enters a URI (like http://wait-till-i.com/index.php) into a user agent (usually a browser).
  2. The browser turns this URI into an IP and requests the file located at the URI specified endpoint.
  3. The browser loads the file and, if it recognizes the document type, tries to display it.
  4. If the document is in HTML, we get an interface that we can interact with; for example, by clicking a link or entering data into a form and submitting it.
  5. In both cases, the whole document is replaced and the sequence restarts.

This has worked since the beginning of the Web and has become expected behaviour for Web surfers. With AJAX, we disrupt this sequence of events. Instead of reloading the document or loading a new one, we replace only a part of the interface, either when the user requests it or automatically every few seconds to display new information.

The benefits of AJAX are pretty clear:

  • We maintain a consistent interface, rather than discard it only to bring it up again with a few slight changes after a long and annoying loading process.
  • We request only the data that we need, when we need it, saving us a lot of server traffic.
  • We are able to offer data without wrapping HTML around it to make it an interface.
  • We allow for simultaneous interaction; a user would be able, for example, to fill out a form while an attachment uploads in the background.

However, with great power comes great responsibility, and with AJAX we have taken it upon ourselves to simulate browser behavior for end users.

AJAX Should Not Break The Web

The first thing to make sure of is that you do not break the Web with your AJAX solutions. The above example would, though:

<div id="target"></div>
<p><a href="#" class="ajaxtrigger">Let there be AJAX magic</a></p>

This is not useful HTML. If JavaScript is not available or anything else goes wrong, you would be offering the end user a link that goes nowhere. This is annoying; I’ve come to your website, took the step of clicking a link, got excited by the prospect of awesome content but don’t get anything. Not good. So, rather than keep the URI in the JavaScript part of the AJAX solution, leave it in the HTML:

<div id="target"></div>
<p><a href="ajaxtest-fullpage.html" class="ajaxtrigger">
  Let there be AJAX magic
</a></p>

This would ensure that the link works; if there is a JavaScript error, the browser would simply move on to load and display ajaxcontent.html. The jQuery code would change accordingly:

$('.ajaxtrigger').click(function(){
  var url = $(this).attr('href');
  $('#target').load(url);
  return false;
});

Instead of hard-wiring a URI to load, we just read the href attribute of the link. The return false is needed to stop the browser from following the link after jQuery has initiated the AJAX request. This also means that any link with the class ajaxtrigger will load content via AJAX and display it in the element with the ID target. You can try this reusable AJAX example here.

There is a problem, of course, because the document we load might be a full HTML document, with a head and a body and so on. This works well in the browser, but the AJAX request would load and inject this document it into another document, which is invalid HTML and would cause display issues. Try this out by clicking the “Load a full document” link on the page referred to above.

Let’s say that ajaxtest-fullpage.html is the following:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  [... some links and title and so on ...]
</head>
<body>
<div id="doc" class="yui-t7">
  <div id="hd" role="banner"><h1>Excerpt from Alice's Adventure Underground</h1></div>
  <div id="bd" role="main">
    <blockquote
     cite="http://ia341030.us.archive[...]-h.htm">
      <p>Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had  peeped into the book her sister was reading, but it had no pictures or conversations in it, and where is the use of a book, thought Alice, without pictures or conversations? So she was considering in her own mind, (as well as she could, for the hot day made her feel very sleepy and stupid,) whether the pleasure of making a daisy-chain was worth the trouble of getting up and picking the daisies, when a white rabbit with pink eyes ran close by her.</p>
    </blockquote>
    <p>Excerpt taken from
      <a href="http://ia341030.us.archive[...]-h.htm">archive.org</a>.
    </p>
  </div>
  <div id="ft" role="contentinfo">
    <p>Demo by <a href="http://wait-till-i.com">Chris Heilmann</a></p>
  </div>
</div>
</body>
</html>

jQuery is all about selectors, which is why the load() function allows you to cut down on the returned HTML by defining a selector. This means that you can change the script to the following (you can try the selector filtering example for yourself):

$('.ajaxtrigger').click(function(){
  var url = $(this).attr('href');
  $('#target').load(url+' #bd blockquote');
  return false;
});

This loads only the blockquote into the other document, so you wouldn’t be creating invalid HTML with the AJAX call. However, we lose the other benefit of AJAX, which is to load less content. If the page is 100 KB and you want to show only the main text, which is 2 KB, why should your users have to wait for 98 KB to load?

To work around this, you need to go server-side. In PHP, you can get information about the request that was sent to load the page. One bit of information is the request method; JavaScript libraries such as jQuery send a specific header across when they load a document with AJAX. You can use this in PHP to set up conditional content:

<?php if($_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest'){?>
This is content requested by AJAX.
<?php }?>

<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){?>
This is the normal content requested in a browser
<?php }?>

Try this header, switching out example for yourself: click the “Load a document with AJAX” link, and then right-click (or Command-click) the same link to open it in a new tab (or hit the “Load the same document without AJAX” link). The results should be “This is content requested by AJAX” and “This is the normal content requested in a browser” respectively.

This way, you can keep all of the header and footer information in includes and load them only when the request could not be done with AJAX. Try the header includes example to see it in action:

<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){?>
  include('header.php');
<?php }?>

<blockquote
 cite="http://ia341030.us.archive[...]-h.htm">
  <p>Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, and where is the use of a book, thought Alice, without pictures or conversations? So she was considering in her own mind, (as well as she could, for the hot day made her feel very sleepy and stupid,) whether the pleasure of making a daisy-chain was worth the trouble of getting up and picking the daisies, when a white rabbit with pink eyes ran close by her.</p>
</blockquote>
<p>Excerpt taken from
  <a href="http://ia341030.us.archive[...]-h.htm">archive.org</a>.
</p>

<?php if($_SERVER['HTTP_X_REQUESTED_WITH']==''){?>
  include('footer.php');
<?php }?>

Using this “unobtrusive AJAX” approach does a few things:

  • You don’t create broken links, ever.
  • You make it easier to maintain functionality; no need to hunt for URIs in the JavaScript—everything is in the HTML.
  • You allow users to open links in another window or tab.
  • You maintain the AJAX-enabled and AJAX-disabled content in the same document without duplicating content.

“Unobtrusive JavaScript” is the term for this method of developing highly interactive websites. It was coined by Stuart Langridge in 2002, and I wrote a self-training course for it in 2004. Incidentally, Stuart was also the first author to cover AJAX in a JavaScript book, the unfortunately named DHTML Utopia. My own not-quite-so-succinctly-titled book Beginning JavaScript with DOM Scripting and AJAX was, I think, the second. Both books follow the approach shown here and create AJAX solutions that fall back to non-JavaScript versions.

Jeremy Keith tried to further popularize this idea of “safer AJAX” in 2006 by calling it “Hijax”, and he wrote a book titled Bulletproof AJAX in 2007. Sadly, though, I have encountered people who use this as an excuse, saying, “We’re building an AJAX solution now, and we’ll move it to Hijax later.” This will not work! Do it right the first time and you’ll have a stable solution. There is no “We’ll fix it in the next iteration” when it comes to essential functionality in Web development: 12 years of professional development have taught me that much.

AJAX Design Challenges

In dealing with AJAX as designers, we have to reconsider the ways in which we define interfaces. Rather than concentrate on the look and feel of the page and subsequent pages, we need to drill down to an atomic level. Each part of an AJAX interaction needs to be defined. Also, think about non-JavaScript versions of widgets.

With AJAX interfaces, we move into a world of applications that have states and views and out of a world in which our document or page model was based on ideas carried over from print. This for me is a good thing. The Web is a rich medium, not a sequence of linked designs.

AJAX And Usability

As mentioned, we use AJAX to disrupt the normal browsing behaviour of our users. This can be a good thing: no one claims that browsers do everything right, but understanding just how many things we should take care of when taking over the browser is important.

What Browsers Do That You Need to Simulate

We sometimes forget just how many things the browser does for us:

  • When we click a link, an indicator alerts us to a loading process (whether an animated icon, progress bar, etc.).
  • For large files, the progress bar gives us an idea of how far we’ve reached in the loading process.
  • If we get tired of waiting, we can hit the “Stop” button or try again by reloading the page.
  • If a page cannot be found, we are shown an error page.
  • If a page takes too long to load, we are shown an error page.
  • Other errors we encounter (for example, a page that needs authentication, or a document that has been moved) are also displayed on a special page.
  • We can right-click a link to open it in a new tab or window, instead of replacing the current document.
  • We can bookmark a page and come back to it at any time in the future.
  • When we need to undo something that’s gone wrong, a “Back” button takes us back one step in our journey.

All of this needs to be accounted for in a full-fledged AJAX application, because AJAX should improve the end user’s experience rather than make it harder. Let’s now enhance our AJAX script until we can say that we’ve covered the basics.

Bookmarking and the Back Button

One thing I won’t go into in detail is the “Back” button and bookmarking functionality. To make this work, you need to update the URI of the current page with a fragment and reload a hidden frame in the page. There are all kinds of annoying differences between browsers, too, and you can use something like the history plug-in for jQuery to get this to work.

Alerting the User That Something Is Loading

Probably the first thing to fix is to tell the user that something is loading when they click a link or push a button. If the page shows no apparent change, the user will think something is wrong and keep clicking. This is an unfortunate human reflex, because the more you tell a computer to do something, the slower and more confused it gets.

A simple way to provide the user with feedback is to show a loading message. To do this in jQuery, we need to get away from the load() method and instead use ajax(), which gives us information about what happens to the request, such as:

  • The beforeSend event that is fired before the AJAX request is initiated, and
  • The success event that is fired when the AJAX request is successful.

Putting them together, we can add a loading message to the target element when the AJAX request starts, which is replaced when the data has successfully loaded:

$(document).ready(function(){
  var container = $('#target');
  $('.ajaxtrigger').click(function(){
    doAjax($(this).attr('href'));
    return false;
  });
  function doAjax(url){
    $.ajax({
      url: url,
      success: function(data){
        container.html(data);
      },
      beforeSend: function(data){
        container.html('<p>Loading...</p>');
      }
    });
  }
});

Error Handling

As you may have guessed, the next logical step is to handle error cases. This is something far too many AJAX solutions haven’t gotten right, and seeing a great application become useless just because one call has timed out is very frustrating.

We have to prepare for three different errors:

  • The user tries to load an external file that is not available because of AJAX security settings;
  • There is some server error (for example, “Page not found”);
  • The resource takes too long to load.

The following script takes care of all this, and you can see it in action on the error handling demo page.

$(document).ready(function(){
  var container = $('#target');
  $('.ajaxtrigger').click(function(){
    doAjax($(this).attr('href'));
    return false;
  });
  function doAjax(url){
    if(url.match('^http')){
      var errormsg = 'AJAX cannot load external content';
      container.html(errormsg);
    } else {
      $.ajax({
        url: url,
        timeout:5000,
        success: function(data){
          container.html(data);
        },
        error: function(req,error){
          if(error === 'error'){error = req.statusText;}
          var errormsg = 'There was a communication error: '+error;
          container.html(errormsg);
        },
        beforeSend: function(data){
          container.html('<p>Loading...</p>');
        }
      });
    }
  }
});

The changes are:

  • We test whether the link URI starts with http and then report an error that loading it with AJAX is not possible.
  • If the link doesn’t begin with http, we start a new AJAX request. This one has a few new features:
    • We define a timeout of 5 seconds (i.e. 5000 milliseconds);
    • We add an error handler.
  • The error handler either sends us what happened on the server as req.statustext or gives us the error message timeout when the 5 seconds are up. So, we need to check what we got before we write out the error message.

Highlighting Changes

We’re almost done enhancing the usability of our AJAX solution. One last touch is to make it very obvious that something on the page has changed. The standard way of doing this is called the yellow fade and was introduced in 2004 by 37signals in its Basecamp application.

With this technique, you change the background colour of the element to yellow and then fade it smoothly back to white. This grabs the user’s attention without overloading them (unlike zooming in on the content in or popping it up, PowerPoint style, which would overwhelm), and it is pretty easy to implement.

jQuery has a plug-in in the effects package called Highlight that does exactly that. Using it, we can highlight the AJAX returns, making it very obvious that something has changed:

$(document).ready(function(){
  var container = $('#target');
  $('.ajaxtrigger').click(function(){
    doAjax($(this).attr('href'));
    return false;
  });
  function doAjax(url){
    if(url.match('^http')){
      var errormsg = 'AJAX cannot load external content';
      container.html(errormsg).
        effect('highlight',{color:'#c00'},1000);
    } else {
      $.ajax({
        url: url,
        timeout:5000,
        success: function(data){
          container.html(data).
            effect("highlight",{},1000);
        },
        error: function(req,error){
          if(error === 'error'){error = req.statusText;}
          var errormsg = 'There was a communication error: '+error;
          container.html(errormsg).
            effect('highlight',{color:'#c00'},1000);
        },
        beforeSend: function(data){
          container.html('<p>Loading...</p>');
        }
      });
    }
  }
});

Notice the different colors for the error case and success case.

This is about all we need to do to make AJAX more usable. But to make it accessible to everyone out there, we have to do a bit more.

AJAX And Accessibility

Accessibility does not mean much more than hard-core usability. If the “average” user is confused by an interface that doesn’t work as they expect, imagine the predicament of users who cannot see the interface at all. Or think someone who has trouble noticing changes from one page to the next and all of a sudden has to deal with small changes on individual pages—changes they are not notified about. Imagine a keyboard user tabbing through a document to activate a link and out of the blue being confronted by 10 more links. There are a lot more cases such as these, and your interface should be able to handle them at least at a very basic level.

Much Ado About Screen Readers

If you research the topic of AJAX and accessibility, you will come across a lot of tutorials that deal with the problem of screen readers. I won’t go into details—this could be its own article—but here are the main points:

  • Screen readers are tools that read out to visually impaired users what is on the screen (or in the HTML and hidden by CSS).
  • Screen readers work on top of the normal browser and enhance its functionality. Specifically, they allow for quicker keyboard navigation (for example, jumping from headline to headline with a shortcut).
  • They take a copy of a document after it has loaded and apply changes to it.
  • This means that screen readers understand JavaScript, but they only execute a request when the page has loaded. If you change a document with JavaScript and AJAX after it has loaded, you need to notify the screen reader somehow that something has changed and refresh the copy of the page. This can be done by refreshing a form field as a hack.

The real problem with screen readers, and any assistive technology, is that they add yet another level of complexity to our Web interaction.

We have HTML interfaces such as links and forms that need to work with all kinds of input devices: keyboard, mouse, voice recognition software, to name a few. Then the browser needs to somehow tell the assistive software (whether a screen reader or software that zooms the screen or a voice recognition tool) that something has changed, and that other tool has to translate it into an understandable format. All of this can, and frequently does, fail.

Much like how HTML 5 is being pushed to replace HTML 4 because the latter is not rich enough to support the interfaces we want to build, WAI-ARIA is a standard that works around the problem of assistive technology and browsers not talking to each other.

With WAI-ARIA, you can tell a screen reader, for example, that a particular element on the page changes frequently and will be refreshed with AJAX. Again, this topic is too big to cover here, but some good articles are out there in case you are interested.

Important Feature #1: Keyboard Access

One very important requirement of accessibility and AJAX is providing keyboard access, and doing this in a very basic way is not hard. The element that triggers the AJAX call has to be something that users can access with the keyboard (i.e. either a link or a button). You can test this yourself: simply use the Tab key to jump from one keyboard-accessible element to the next in your document. Can you access all of the functionality, and is it obvious where you are at any given moment?

This is where you as a designer can do a lot to make your AJAX interface more accessible. Patrick Lauke has written a wonderful article on keyboard-access styling to get you on your way.

Important Feature #2: Notify at the Source

The second, very important, part is to notify users in the element that they activated that something is happening. You’ll often see interfaces where the activation button or link is in one spot but the content gets loaded somewhere else on the screen. One example of this is the contact form on Get Satisfaction:

Get-satisfaction-small2 in Developing Sites With AJAX: Design Challenges and Common Issues
Large view

When we can see the screen in full, everything is pretty obvious. But consider an end user who has to magnify the screen to 1600% to be able to read it. Or someone who gets easily confused and uses a tool to focus on the part of the screen they are interacting with and blur out the rest. Their experience is different:

Zoomed in Developing Sites With AJAX: Design Challenges and Common Issues

By clicking this, the user expects to be able to submit feedback. Instead, all they get is a darker screen, which could be a hardware problem (running out of battery?) or something else entirely. They have no information on which to base their next move.

You don’t even have to go as far as considering people with disabilities: just use a netbook whose viewport is a mere 300-pixels high (like my first-generation Eee PC) or a mobile interface that zooms into a certain part of the page (like my Blackberry with Opera Mini).

In any of these cases, your AJAX solution will be neither usable nor accessible if the section that is replaced is far removed from the button that fires the AJAX request.

You have two workarounds. The most obvious one is to keep the elements close together. If that is not possible, the other workaround is to change the content of the element that fires the AJAX request once the user clicks on it. This indicates to the end user what is going on.

Notifications in Developing Sites With AJAX: Design Challenges and Common Issues

As an added assistance, you can shift the keyboard focus to the target element when the AJAX request has been processed. Be aware, though, that this could confuse some users; being jumped around the screen without meaning to can be scary. Pretty, smooth-transitioning solutions look good to the rest of us, but they can be a total nightmare for users with learning disabilities.

Putting all of this together, take a look at this more accessible example. It adds a span to the link to show the state of the AJAX request, it highlights the content when it has finished loading, and then it shifts the focus to the new element. Here is the final code. Check the comments (// example) to see what is going on.

$(document).ready(function(){

  // this is the container we'll load content into
  var container = $('#target');

  // adding a tabIndex of -1 makes it keyboard accessible,
  // and we can set the focus to it
  container.attr('tabIndex','-1');

  // if a user clicks on an element with the class ajaxtrigger...
  $('.ajaxtrigger').click(function(){

    // define trigger as the link
    var trigger = $(this);

    // read its href attribute (which is the URI we'll load with AJAX)
    var url = trigger.attr('href');

    // if the element does not have a class called "loaded"
    if(!trigger.hasClass('loaded')){

      // add a new span to the element.
      trigger.append('<span></span>');

      // add a class called 'loaded' to the element
      trigger.addClass('loaded');

      // and define msg as the last span in the element
      var msg = trigger.find('span::last');

    // otherwise, simply define msg as the last span in the element
    } else {
      var msg = trigger.find('span::last');
    }
    // ^ this condition means we only add the span once and not
    //   every time users click the element.

    // call the doAjax function with the URI to load,
    // the span inside the link to change and the
    // target element to replace.
    doAjax(url,msg,container);

    // tell the browser to not follow the link
    return false;
  });

  // here's where the AJAX magic happens
  function doAjax(url,msg,container){

    // if the URI starts with http...
    if(url.match('^http')){
      // show an error and set the class of the span to 'error'
      msg.html(' (error!)').addClass('error');

      // tell the end user in the target element what the error is
      var errormsg = 'AJAX cannot load external content';

      // update the container with the error
      updateContainer(errormsg,'#c00');

    // if the URI does not start with http
    } else {

      // start an AJAX request using the url
      $.ajax({
        url: url,

        // give the request five seconds time, otherwise call it
        // a timeout error
        timeout:5000,

        // if all went well
        success: function(data){

          // set the span content to ready
          msg.html(' (ready.)');

          // update the container with the right data
          updateContainer(data,'#ff9');
        },

        // if there was an error
        error: function(req,error){

          // say in the link that there was an error and set the
          // class of the span to 'error'
          msg.html(' (error!)').addClass('error');

          // if the error just says error, get the real status
          // text from the browser (jQuery doesn't do this right)
          if(error === 'error'){error = req.statusText;}

          // tell the user that there is a communication error
          var errormsg = 'There was a communication error: '+error;

          // update the container with the error
          updateContainer(errormsg,'#c00');
        },

        // if the link was clicked but the AJAX request was not fired...
        beforeSend: function(data){

          // remove any "error" classes and set the span message to loading
          msg.removeClass('error').html(' (loading...)');
        }
      });
    }
  };

  // update the container
  function updateContainer(content,colour){
    container.
      // set the content
      html(content).
        // shift the browser focus
        focus().
          // flash the container for a second in the
          // specified colour
          effect('highlight',{color:colour},1000);
  }

});

The code is a bit longer than in that our other examples, but the payoff makes it very much worthwhile.

Important Feature #3: De-Clutter Your Interface

With a library such as jQuery, you can make anything on the page interactive and make it initiate AJAX requests. You could use roll-overs or drag-and-drop interfaces, and these are great to look at, but ask yourself: are they really intuitive? Browsers do not yet have any drag-and-drop functionality or even roll-overs. Roll over your menu bar; you have to click to initiate any action.

But by using JavaScript tricks, you can make any element keyboard accessible. And if you build widgets, go even further by following the rules of keyboard navigation. You could even create a screen reader-compatible drag-and-drop interface. But again, ask yourself a few questions:

  • Is it worth the hassle?
  • Does it really make the interface easier to understand?
  • Does it make it more natural to use?
  • Does it help all users reach their goal faster, or have you implemented the feature just because it looks cool?

Making the interface as simple as possible does not mean neutering your creativity. On the contrary, the easiest and simplest interfaces are the ones that have gone through a lot of research and design iterations. Great usability means not recognizing that something has been done to make the interface easy.

What Not To Use AJAX For

Never rely on AJAX to handle sensitive information, because modern debugging tools allow anyone to see what is happening on the page. Using the Firebug extension, I can get all of the information about the HTTP traffic of a certain document, including the AJAX requests:

Firebug in Developing Sites With AJAX: Design Challenges and Common Issues

By analyzing these requests, I could glean information that you wouldn’t want to show the world; for example, the endpoints of the services on your system (such as mail scripts), which I could exploit for my own purposes.

Nothing in your JavaScript or HTML is secure. I can change it on the fly and work around your protection mechanisms.

If you are not building a Web application but are merely offering articles for people to read or a catalogue to flip through, you probably shouldn’t go the AJAX route anyway.

The other thing to consider is search engines. If you load all of your content with AJAX, you aren’t offering much in your documents for search engines to index. Static HTML content is still best for search engine indexing—as well as performance, because pages can be packed and cached nicely on your server, if you do it right. Loading via AJAX brings up the content much faster for users and saves on bandwidth, but you will see less traffic from search engines. Something to consider.

The External Content Problem

One built-in security setting of AJAX is that you cannot load content on another server. This is critical, otherwise people would be able to call and inject whatever script they please from the Web. Definitely a bad idea.

You may sometimes need, though, to retrieve third-party content; i.e. load external content in your document as data (because you can always use iFrames to embed other documents). This is where we have to get clever with the technologies at our disposal.

The most common workaround for AJAX not being able to load something like http://icant.co.uk/index.php is to write a server-side script that loads the page and then prints it out. This is called a proxy, and you can see an example of the solution here.

Of utmost importance when using a proxy is to whitelist the URIs that you want to load. Do not simply load any URI off the Web, or else attackers would be able to read files from your server and use your server to send out spam and attack other servers, making it look as though you were the perpetrator.

Other ways to retrieve external content is by getting data in a special format called JSON-P or by using a hosted proxy service such as YQL. I’ll keep this brief because there are several solutions to this problem. If you are interested in learning more, check out this blog post on the subject.

What To Use AJAX For

When used wisely, AJAX makes our life on the Web easier. If you’re wondering when and how to use it, check out the examples in the Design Pattern Gallery, which are based on real user research. For starters, think about these use cases:

  • Adding a large attachment to a message.
    Nothing is more annoying than waiting for your browser to upload something without having a clue how fast and how far along it is. Browser progress bars give us a hint but no real numbers. The Yahoo User Interface uploader, as well as jQuery implementations such as Uploadify, show how that would look like in the browser.
  • Handling a lot of small data sets.
    A great example of this is the comments section in WordPress. Rather than having to click a lot of checkboxes or reload the page every time I want to delete or approve comments, all I do is click a few links.
  • Rating content.
    No need to reload the entire page if you just want a simple Yay or Nay from the user in response to a question.
  • Displaying constantly changing content.
    For example, financial tickers or instant updates from Twitter and Facebook.
  • Add your own use here.

I hope you’ve gained a few more insights into what AJAX is and how you can use it to improve the user experience in a way that is safe and doesn’t leave certain segments of users out in the cold. AJAX makes stuff smoother, but nothing is more annoying than a supposed enhancement spoiling the whole experience.

(al)


© Christian Heilmann for Smashing Magazine, 2010. | Permalink | 67 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: , ,

Tags:

SimpleFolio: A Free Clean Portfolio WordPress Theme

Smashing-magazine-advertisement in SimpleFolio: A Free Clean Portfolio WordPress Theme
 in SimpleFolio: A Free Clean Portfolio WordPress Theme  in SimpleFolio: A Free Clean Portfolio WordPress Theme  in SimpleFolio: A Free Clean Portfolio WordPress Theme

Today we are glad to release a beautiful, simple and clean portfolio WordPress theme — SimpleFolio, designed by Omar E. Corrales and released for Smashing Magazine and its readers. SimpleFolio is a portfolio theme that includes a blog and a very extensive option page that allows you to exclude all your portfolio items from the blog page. It also includes a front page slider.

It has 2 different widget areas and threaded comments, and also supports paged comments and has 2 different page templates for advanced usage. The control of images is done from the post page.

Release in SimpleFolio: A Free Clean Portfolio WordPress Theme

Download the theme for free!

The theme is released under GPL. You can use it for all your projects for free and without any restrictions. You may modify the theme as you wish. Please link to this article if you want to spread the word.

Preview in SimpleFolio: A Free Clean Portfolio WordPress Theme

Features

Here are some of the features of the theme:

  • CSS-based layout,
  • 2 columns of fixed width,
  • widget-ready,
  • XHTML 1.0 Transitional valid,
  • multi-browser compatibility: tested on Firefox, Safari , IE7, IE8, Chrome,
  • easy to setup, theme options page.

Scr2 in SimpleFolio: A Free Clean Portfolio WordPress Theme
Front page

Scr4 in SimpleFolio: A Free Clean Portfolio WordPress Theme
Portfolio

Scr5 in SimpleFolio: A Free Clean Portfolio WordPress Theme
Portfolio

Scr3 in SimpleFolio: A Free Clean Portfolio WordPress Theme
Options page in back-end

Scr6 in SimpleFolio: A Free Clean Portfolio WordPress Theme
Single post, main area

Scr7 in SimpleFolio: A Free Clean Portfolio WordPress Theme
Single post, threaded comments

Scr8 in SimpleFolio: A Free Clean Portfolio WordPress Theme
Single post, sidebar

Behind the design

As always, here are some insights from the designer:

I created this theme after getting tired of all the fancy design themes that are very popular now a days, this is a design for people that just need the job done without complicating them selfs. The best use can be either for just someone thats starting to blog or some artist that needs to expose there art.

Thank you, Omar. We appreciate your work and your good intentions!


© Elja Friedman for Smashing Magazine, 2010. | Permalink | 115 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags:

Tags:

47 Amazing CSS3 Animation Demos

Leadin Image

Here is a compilation of 47 jaw-dropping CSS3 animation demos. They demonstrate the possibilities of the CSS3 transform and transition property. Some are very useful and can be used as Javascript alternatives. Most of them are simply to look cool. In order to veiw these effects, you need a webkit browser such as Safari and Chrome (sorry to the Internet Explorer users). Enjoy!
(more…)

Tags:

50 Brilliant CSS3/JavaScript Coding Techniques

Smashing-magazine-advertisement in 50 Brilliant CSS3/JavaScript Coding Techniques
 in 50 Brilliant CSS3/JavaScript Coding Techniques  in 50 Brilliant CSS3/JavaScript Coding Techniques  in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS3 is coming. Although the browser support of CSS 3 is still very limited, many designers across the globe experiment with new powerful features of the language, using graceful degradation for users with older browsers and using the new possibilites of CSS3 for users with modern browsers. That’s a reasonable solution — after all it doesn’t make sense to avoid learning CSS3 (that will be heavily used in the future) only because these features are not supported yet. The point of this article is to give you a glimpse of what will be possible soon and what you will be using soon and provide you with an opportunity to learn about new CSS3 techniques and features.

In this post we present 50 useful and powerful CSS3/jQuery-techniques that can strongly improve user experience, improve designer’s workflow and replace dirty old workarounds that we used in Internet Explorer 6 & Co. Please notice that most techniques presented below are experimental, and many of them are not pure CSS3-techniques as they use jQuery or other JavaScript-library.

[Offtopic: by the way, have you already visited Smashing Magazine's Facebook fan page? Join the community for a stream of useful resources, updates and giveaways!]

Visual Effects and Layout Techniques With CSS3

CSS3 Analogue Clock
Analogue clock created using webkit transition and transform CSS. JavaScript is only used to pull in the current time.

Css-132 in 50 Brilliant CSS3/JavaScript Coding Techniques

Use CSS3 to Create a Dynamic Stack of Index Cards
We will create a dynamic stack of index cards solely with HTML and CSS3 and use such CSS3 features as transform and transition (for the dynamic effects) and @font-face, box-shadow and border-radius (for the styling).

Css3-new-03 in 50 Brilliant CSS3/JavaScript Coding Techniques

dynamic PNG shadow position & opacity
When the light is turned on, the position and opacity of the logo shadow will change dynamically, depending on the position and distance of the light bulb. Don’t forget to drag the logo and/or the light bulb around!

Css3-new-00 in 50 Brilliant CSS3/JavaScript Coding Techniques

How To Create A Sexy Vertical Sliding Panel Using jQuery And CSS3
So, what about a vertical sliding panel that would act as some sort of drawer instead of the usual top horizontal sliding panel that pushes everything else down when it opens? While thinking of alternatives to the usual horizontal panels, I thought it would be nice to create something that works in a similar way, but that is a bit more flexible.

Css3-last-08 in 50 Brilliant CSS3/JavaScript Coding Techniques

Awesome Overlays with CSS3
The trick with these overlays is the gradient border, going form a lighter to darker orange as you go from top to bottom. To create that effect we used to the border-image property, which is a tricky little addition to CSS.

Css3-last-11 in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS3 & Flexible UI: Avoid Recutting UI Graphics for Mobile
What if we could replace almost all of the graphical UI elements within Fennec with CSS created equivalents? As a designer, am I comfortable bypassing Photoshop and letting CSS run the pixel rodeo? After a few initial tests, the answer to both of those questions was a very solid “yes”. A solid “friggin’ right” if in Cape Breton.

Css-144 in 50 Brilliant CSS3/JavaScript Coding Techniques

How To Create Depth And Nice 3D Ribbons Only Using CSS3
We will use box-shadow to create a drop-shadow with RGBa, a color model that allows an optimized contrast with any kind of backgrounds. RGBa is the standard RGB model (0,0,0 – 255,255,255) and it adds the last option (a) for the opacity. We can use this model also for other properties and it works with the new browser.

Css-197 in 50 Brilliant CSS3/JavaScript Coding Techniques

Create a Beautiful Looking Custom Dialog Box With jQuery and CSS3
This custom dialog box is one of the scripts in that website and I think it will be quite useful for all of us. The reason I have this custom dialog box is to overcome the inconsistencies across different browsers. And, of course, it uses CSS3 to style everything.

Css3-last-00 in 50 Brilliant CSS3/JavaScript Coding Techniques

Drop-In Modals with CSS3
For those using WebKit based browsers (Safari and Chrome), CSS3 effects and properties can help you create fast, simple modals by using transforms, animation, and some subtle design cues.

Css3-last-13 in 50 Brilliant CSS3/JavaScript Coding Techniques

Newspaper Layouts with Columns and Image Masks
The faux-newspaper look goes in and out of style online pretty frequently, but these tricks can be used for quite a few cool applications. What we’ll talk about here is using -webkit-mask-image and -webkit-column-count.

Css3-last-14 in 50 Brilliant CSS3/JavaScript Coding Techniques

Navigation Menus With CSS 3

Sweet AJAX Tabs With jQuery 1.4 & CSS3
This post is a tutorial of making an AJAX-powered tab page with CSS3 and the newly released jQuery 1.4.

Sweet-tabs in 50 Brilliant CSS3/JavaScript Coding Techniques

Sweet tabbed navigation bar using CSS3
Although I don’t understand why animations have been added in CSS3, this upcoming standard does have a couple of very neat features added to the CSS we’re using today. I wanted to take a couple of these new things, and create a Sweet tabbed navigation using CSS3.

Css-041 in 50 Brilliant CSS3/JavaScript Coding Techniques

Halftone Navigation Menu With jQuery & CSS3
Today we are making a CSS3 & jQuery halftone-style navigation menu, which will allow you to display animated halftone-style shapes in accordance with the navigation links, and will provide a simple editor for creating additional shapes as well.

Css3-last-05 in 50 Brilliant CSS3/JavaScript Coding Techniques

Building Coverflow With CSS Transforms
I was able to create a coverflow effect that actually flows and animates in real-time, without using canvas or prerendered graphics.

Css3-last-04 in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS3 Hover Tabs without JavaScript
With the new techniques in CSS3 and clever applications of existing CSS it is increasingly stepping on the toes of JavaScript. Which to be honest isn’t necessarily a bad thing. I thought I’d try my hand at something so here is a basic CSS tabbed content section that changes on hover.

Css-186 in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS 3 Transitions and Animations

Going Nuts with CSS Transitions
I’m going to show you how CSS 3 transforms and WebKit transitions can add zing to the way you present images on your site.

Css-010 in 50 Brilliant CSS3/JavaScript Coding Techniques

Sliding Vinyl with CSS3
We take a standard album cover, a little HTML, and some CSS3 transitions and transforms to create a sliding vinyl effect for showing off the music you love.

Css3-last-12 in 50 Brilliant CSS3/JavaScript Coding Techniques

Fun with CSS3 and Mootols
These examples came about when experimenting with the extend property in MooTools. By extending the styles class I could add CSS3 properties into the Core MooTools framework and do CSS3 animations.

Css3-last-171 in 50 Brilliant CSS3/JavaScript Coding Techniques

Star Wars HTML and CSS: A NEW HOPE
There are a lot of CSS transitions experiments going on right now. Yesterday I discovered another HTML and CSS experiment which went “far far away”, compared with my simple CSS gallery.
Guillermo Esteves presented a piece of history translated for tomorrows browsers: the Star Wars Episode IV opening crawl in HTML and CSS.

Css-130 in 50 Brilliant CSS3/JavaScript Coding Techniques

Fun with 3D CSS and video
Zach Johnson has been having fun with 3D effects via CSS such as his isocube above, which is brought to you with simple HTML (including a video tag for a playing video on the surface!) and some CSS.

Css-138 in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS3 animations and their jQuery equivalents
This tutorial/these examples will show the use of the same HTML, with different classes for CSS3 and jQuery. You can compare both the codes and see which one you like more. Don’t forget to check the demo/download the source code to view how everything is working under the hood.

Css-040 in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS Animations
No matter how fast internet tubes or servers are, we’ll always need spinners to indicate something’s happening behind the scenes.

Css-009 in 50 Brilliant CSS3/JavaScript Coding Techniques

Snowy CSS3 Animation
It’s cold and snowy down here in Brighton, so to celebrate the falling white stuff (and of course the various festivities at this time of year) Clearleft’s very own Natbat has made a snowy CSS3 animation surprise for all you Safari and Chrome users out there.

Css-005 in 50 Brilliant CSS3/JavaScript Coding Techniques

What You Need To Know About Behavioral CSS
In this article, we will take those properties a step further and explore transformations, transitions, and animations. We’ll go over the code itself, available support and some examples to show exactly how these new properties improve not only your designs but the overall user experience.

Css-038 in 50 Brilliant CSS3/JavaScript Coding Techniques

3D Cube using new CSS transformations
The impression of a three dimensional cube can be created using modern CSS techniques, without the need for JavaScript, imagery, canvas or SVG. Using the proprietary transform property to skew and rotate shaded rectangles, individual cube faces can combine to form a 3D object.

Css-139 in 50 Brilliant CSS3/JavaScript Coding Techniques

Playing around with WebKit Animations
I’ve been playing around doing a KeyNote like animation done with CSS and some JS to hook up the necessary events. The animation is kind of like a deck of cards. When you go to the next one the current one zooms in and fades out, symbolizing getting closer to the viewer. The next card then zooms and fades in from the back and to give a fancy effect-

Css-133 in 50 Brilliant CSS3/JavaScript Coding Techniques

More on 3D CSS Transforms
Various 3D CSS Transforms in an overview.

Css3-last-15 in 50 Brilliant CSS3/JavaScript Coding Techniques

Gradients, RGBA and HSL with CSS 3

Working With RGBA Colour
CSS3 introduces a couple of new ways to specify colours, and one of those is RGBA. The A stands for Alpha, which refers to the level of opacity of the colour, or to put it another way, the amount of transparency. This means that we can set not only the red, green and blue values, but also control how much of what’s behind the colour shows through. Like with layers in Photoshop.

Css-007 in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS3 Gradients: No Image Aqua Button
I played around with WebKit CSS3 gradient and created a useless but fun stuff – an Aqua button with no images! Back in the time when Mac OS X was first announced, there’re a plenty of web tutorials that describe how to create the sexy aqua button with Photoshop, and now I can show how to create one with CSS!

Css-164 in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS3 HSL & HSLA
A tutorial on using the HSL & HSLA declarations along with the quick + / – guide to which browsers currently support the herein effect.

Css3-last-06 in 50 Brilliant CSS3/JavaScript Coding Techniques

Super Awesome Buttons with CSS3 and RGBA
One of our favorite things about CSS3 is the addition of RGBA, a color mode that adds alpha-blending to your favorite CSS properties. We’ve kicked the tires on it a bit with our own projects and have found that it helps streamline our CSS and makes scaling things like buttons very easy. To show you how, we’ve cooked up an example with some super awesome, scalable buttons.

Css-100 in 50 Brilliant CSS3/JavaScript Coding Techniques

Using the Shadow-Property in CSS3

Create a Letterpress Effect with CSS Text-Shadow
The letterpress effect is becoming hugely popular in web design, and with a couple of modern browsers now showing support for the text-shadow CSS3 property it’s now simple and easy to create the effect with pure CSS. No Photoshop trickery here!

Css-096 in 50 Brilliant CSS3/JavaScript Coding Techniques

Shadows and CSS3
I’m currently working on a design that uses text-shadow and box-shadow, with RGBA in place to create the shadow color. I wanted to tweet about this technique because it’s simple and awesome, but to my surprise I couldn’t find a good, quick tutorial that covered the use of both text and box-shadow, along with RGBA. So I decided to create one.
I learned this technique from Dan Cederholm’s Handcrafted CSS book, so if you’re able I’d recommend just going out and grabbing that, as he explains it much more elegantly and thoroughly than I ever could.

Css-003 in 50 Brilliant CSS3/JavaScript Coding Techniques

Learning New CSS3 Selectors

CSS3 + Progressive Enhancement = Smart Design
Progressive enhancement is a good thing, and CSS3 is even better. Combined, they enable designers to create lighter, cleaner websites faster and easier than ever before.

Css3-new-01 in 50 Brilliant CSS3/JavaScript Coding Techniques

A Look at Some of the New Selectors Introduced in CSS3
Here is a run-down of just some of the things that is possible with CSS3 selectors. Of course CSS3 isn’t supported at all by any IE browsers including IE8 but all latest versions of Safari, Firefox and Opera support most, if not all of them.

Css-168 in 50 Brilliant CSS3/JavaScript Coding Techniques

Cleaner Code with CSS3 Selectors
In this article I’m going to take a look at some of the ways our front and back-end code will be simplified by CSS3, by looking at the ways we achieve certain visual effects now in comparison to how we will achieve them in a glorious, CSS3-supported future. I’m also going to demonstrate how we can use these selectors now with a little help from JavaScript – which can work out very useful if you find yourself in a situation where you can’t change markup that is being output by some server-side code.

Css-008 in 50 Brilliant CSS3/JavaScript Coding Techniques

The CSS3 :target Pseudo-class And CSS Animations
It’s no secret that I’m always looking for an easy way out using CSS instead of trying to replicate things with convoluted code — there are so many underused techniques that we could be applying to our designs as an enhancement layer! In this experience, I take a brief look into the :target pseudo-class and a very simple CSS animation.

Css3-last-01 in 50 Brilliant CSS3/JavaScript Coding Techniques

The CSS3 :not() selector
There isn’t a lot of information to be found about the :not() selector. The specifications only offer 3 lines of text and a couple of examples. So lets see what it can do!

Css3-last-02 in 50 Brilliant CSS3/JavaScript Coding Techniques

IE CSS3 pseudo selectors
ie-css3.js allows Internet Explorer to identify CSS3 pseudo-class selectors and render any style rules defined with them. Simply include the script in your pages and start using these selectors in your style sheets — they’ll work in IE… Honest…!

Css3-new-02 in 50 Brilliant CSS3/JavaScript Coding Techniques

CSS3 Galleries

How To Create a Pure CSS Polaroid Photo Gallery
Magical things can be done by combining various CSS properties, especially when some of the new CSS3 tricks are thrown into the mix. Let’s take a look at building a cool looking stack of Polaroid photos with pure CSS styling.

Css-082 in 50 Brilliant CSS3/JavaScript Coding Techniques

An Awesome CSS3 Lightbox Gallery With jQuery
In this tutorial we are going to create an awesome image gallery which leverages the latest CSS3 and jQuery techniques. The script will be able to scan a folder of images on your web server and build a complete drag and drop lighbox gallery around it.

Css-155 in 50 Brilliant CSS3/JavaScript Coding Techniques

If That Is An Awesome CSS3 Gallery, How Would You Call Mine?

Css-136 in 50 Brilliant CSS3/JavaScript Coding Techniques

Editable CSS3 Image Gallery
We build a pretty typical image gallery design pattern, a grid of images that pop up larger when clicked. But this image gallery page makes use of hot semantic HTML5 markup, loads of visual treats with CSS3 and jQuery, and made editable through the CMS PageLime. Quick reminder, the demo is awesome-est in a WebKit browser (Safari or Chrome).

Css-163 in 50 Brilliant CSS3/JavaScript Coding Techniques

Replacing CSS Hacks with CSS 3

Rounded corner HTML elements using CSS3 in all browsers
This is a behavior htc file for Internet explorer to make CSS property ” border-radius ” work on all browsers. At present, all major browsers other than IE shows curved corner by adding 4 lines of css.

Css3-last-03 in 50 Brilliant CSS3/JavaScript Coding Techniques

Using Rounded Corners with CSS3
As CSS3 gets closer to becoming the new standard for mainstream design, the days of rounded corners through elaborate background images is fading. This means less headache and time spent working out alternatives for each browser.

Css-058 in 50 Brilliant CSS3/JavaScript Coding Techniques

Better Image Preloading with CSS3
Using CSS3’s new support for multiple background images, we can use a single, existing element to preload all of the required images.

Css-194 in 50 Brilliant CSS3/JavaScript Coding Techniques

Saying Goodbye to the overflow: hidden Clearing Hack
I’m now saying goodbye to overflow: hidden and the deciding factor for me is CSS3. Specifically box-shadow. At least in the sense that box-shadow was the first property I noticed being negatively impacted by the use of overflow: hidden. Like the positioned child elements mentioned above, box-shadow can get clipped when the parent (or other ancestor) element has overflow applied. And there are several other things to consider as we move forward using more CSS3. Text-shadow and transform can also potentially be clipped by overflow: hidden.

Css-184 in 50 Brilliant CSS3/JavaScript Coding Techniques

General articles about CSS 3

How to bring CSS3 features into your design
Top web browser (such as Firefox 3.5 and Safari 4) have introduce some cool features you can already use. Now, with just a few lines of css you can do things you used to do with images and javascript.

Css-013 in 50 Brilliant CSS3/JavaScript Coding Techniques

Practical Uses of CSS3
In this article I’ll show you some practical uses for CSS3.

Css-032 in 50 Brilliant CSS3/JavaScript Coding Techniques

11 Classic CSS Techniques Made Simple with CSS3
We’ve all had to achieve some effect that required an extra handful of divs or PNGs. We shouldn’t be limited to these old techniques when there’s a new age coming. This new age includes the use of CSS3. In today’s tutorial, I’ll show you eleven different time-consuming effects that can be achieved quite easily with CSS3.

Css-122 in 50 Brilliant CSS3/JavaScript Coding Techniques

Mobile optimised websites using CSS3 Media Queries
A while ago I wrote about using CSS3 Media Queries on my website redesign to provide mobile visitors with an optimised view designed for smaller screens. I thought it might be useful if I went into a bit more detail on how I’m doing this.

Css-023 in 50 Brilliant CSS3/JavaScript Coding Techniques

Code a Backwards Compatible, One Page Portfolio with HTML5 and CSS3
HTML5 is the future of web development but believe it or not you can start using it today. HTML5 is much more considerate to semantics and accessibility as we don’t have to throw meaningless div’s everywhere. It introduces meaningful tags for common elements such as navigations and footers which makes much more sense and are more natural. This is a run through of the basics of HTML5 and CSS3 while still paying attention to older browsers. Before we start, make note of the answer to this question. Do websites need to look exactly the same in every browser?

Css3-new-07 in 50 Brilliant CSS3/JavaScript Coding Techniques

Get the best out of CSS3
Craig Grannell turns into a cross between Jeffrey Zeldman and Russell Grant, taking a peek at what the future of CSS has to offer – with a little help from Opera, Safari and Firefox

Css3-last-07 in 50 Brilliant CSS3/JavaScript Coding Techniques

Practical Uses of CSS3
“One big item for me is how much we use CSS3. Yes I know, it is not fully supported across all browsers. If you still want everything to look exactly the same across all browsers, you should probably just close this article and not read about CSS for another 10 years. A user is not going to pull up your site in two different browsers to compare the experience, so they won’t even know what they are missing. Just because something is not fully supported, that does not mean that we can’t use it to an extent. In this article I’ll show you some practical uses for CSS3.”

Css3-last-09 in 50 Brilliant CSS3/JavaScript Coding Techniques

A Crash-Course in Advanced CSS3 Effects
This video tutorial reviews a bunch of different neat effects that can be used in Safari 4, Chrome, and for all iPhone development.

Css3-last-10 in 50 Brilliant CSS3/JavaScript Coding Techniques

33 Must Read CSS3 Tips, Tricks, Tutorial Sites and Articles
An extensive overview of CSS3-techniques, tools, articles and resources.


© Smashing Editorial for Smashing Magazine, 2010. | Permalink | 53 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: ,

Tags:

The New Hotness: Using CSS3 Visual Effects

Smashing-magazine-advertisement in The New Hotness: Using CSS3 Visual Effects
 in The New Hotness: Using CSS3 Visual Effects  in The New Hotness: Using CSS3 Visual Effects  in The New Hotness: Using CSS3 Visual Effects

Previously in this series on CSS3, we talked not only about how to create scalable and compelling buttons but about how to effectively use new CSS3 properties to speed up development and quickly create rich page elements. In this final article of the series, we’ll really get into it and use CSS3 visual effects to push the envelope.

Not everything in this article is practical, or even bug-free, but it’s a fun primer on what’s in the pipeline for Web design. To get the most from these examples, you’ll have to use Safari 4 or Chrome. (Firefox 3.5 can handle most of it, but not everything: WebKit is further along than Gecko in its tentative CSS support.) We’ll show you how to create impressive image galleries, build animated music players and overlay images like a pro. All set? Let’s rock.

[Offtopic: by the way, have you already visited Smashing Magazine's Facebook fan page? Join the community for a stream of useful resources, updates and giveaways!]

Create A Polaroid Image Gallery

Hotness-1 in The New Hotness: Using CSS3 Visual Effects

We always try to stay pretty active with our Flickr feed; our chief instigator Bryan does a great job of capturing the day-to-day and special events and even some of our old work. We wanted a great way to show off these photos, so we turned to CSS3 to create a compelling, fun image gallery. The Polaroid style is pretty common, but we wanted not only to make it dead-simple to create the gallery in the markup but also to add styles that would have required Javascript just a year or two ago.

The Polaroid Gallery Markup

First off, we created very simple markup for the gallery, something that would be easy to generate automatically using the Flickr API. The markup for the entire gallery looks like this:

<ul class="polaroids">
	<li>
	   <a href="http://www.flickr.com/photos/zurbinc/3971679981/" title="Roeland!">
	   	<img src="image-01.jpg" width="250" height="200" alt="Roeland!" />
	   </a>
	</li>
	<li>
	   <a href="http://www.flickr.com/photos/zurbinc/3985295842/" title="Discussion">
	   	<img src="image-02.jpg" width="250" height="200" alt="Discussion" />
	   </a>
	</li>
</ul>

We’ll be using the title element in a minute.

The Base Style and Labels

Our next step was to create the simple Polaroid look. We placed our image inside an anchor with a white background and scaled the image container. This gave us space for the image labels, which we created using little-known CSS tricks: :after and content: attr.

ul.polaroids a:after {
	content: attr(title);
}

What we’re doing here is telling the browser that after it renders the given anchor content, add another piece of content. We then generate that piece of content with the content: attr(title) element, which pulls a specific attribute from the element, in this case the title attribute. Using alt would make more sense, but neither Safari nor Firefox has implemented it for the content element.

The snippet above tells the browser to take the title attribute and render it immediately after the content. Note that the title attribute will be rendered within the anchor, which is exactly what we want. We would have liked to have used the alt attribute, but Safari and Firefox do not support the use of content with it.

Our styling of the anchor element takes care of the formatting of the title attribute as well, and we’ve now placed the image title attribute below it so that we don’t have to replicate that content in the markup.

Scattering the Pictures

A handful of Polaroids would never be in a perfect grid; they’d be scattered over the table. We compromised by messing up the grid a little bit for each image: a little rotation here, some displacement there. However, we did not want to have to manage that scattering on a per-image basis, so we used another new pseudo-class: nth-child.

/* By default, we tilt all images by -2 degrees */
ul.polaroids a {
	-webkit-transform: rotate(-2deg);
	-moz-transform: rotate(-2deg);
}

/* Rotate all even images 2 degrees */
ul.polaroids li:nth-child(even) a {
	-webkit-transform: rotate(2deg);
	-moz-transform: rotate(2deg);
}

/* Don't rotate every third image, but offset its position */
ul.polaroids li:nth-child(3n) a {
	-webkit-transform: none;
	-moz-transform: none;
	position: relative;
	top: -5px;
}

These are only a few of the declarations we used; we actually added them for everything up to 11n, but you get the idea. As you can see, nth-child supports a few different arguments, including even, odd and Xn (where X can be any integer). The even and odd declarations are self-explanatory. Xn takes every Xth element and applies a particular style; in this example, every 3rd. Combining this with odd, even and some more Xn declarations means that even though the style won’t really be random, it will appear random enough to the average user. You can see the entire set of styles on our demo page.

We’re using a new CSS3 property here as well: the CSS transform (shown as -webkit- and -moz-transform). The transform property can take a number of arguments for different kinds of transformations; in this example, we’ll be using rotate and scale. You can see the complete (tentative) list in the Safari Visual Effects Guide.

Some Final Animation

Our last touch was to give the image focus on hover; in this case, to enlarge and straighten out. We accomplish this using a -webkit-transition that is activated by the :hover pseudo-class. Check it out:

ul.polaroids a:hover {
	-webkit-transform: scale(1.25);
	-moz-transform: scale(1.25);
	-webkit-transition: -webkit-transform .15s linear;
	position: relative;
	z-index: 5;
}

What’s happening here is that we’re overriding the existing -webkit-transform to simply scale the image (this eliminates the rotation). The -webkit-transition tells Webkit-based browsers to animate the transform so that the move from one to another is smooth. -webkit-transition is actually extremely versatile, because it can just as easily support color, position (top, right, etc.) and most any other property.

That’s how we created our Polaroid gallery. Once you know these new tricks, putting them together is actually pretty easy, and the markup is dead simple.

Polaroid-images-th in The New Hotness: Using CSS3 Visual Effects

See the Live Demo »

We’ve created a live demo page for this gallery in our Playground, a place for us ZURBians to create small side projects and samples of cool toys. We’ll be linking to the Playground examples throughout this article.


Sliding Vinyl Albums With CSS Gradients

Hotness-2 in The New Hotness: Using CSS3 Visual Effects

This example began as a simple experiment with CSS gradients and grew into a pretty detailed investigation not just of gradients but of new background properties and animation. We’ll show you how to create advanced gradients with no images and use layered backgrounds for some cool effects.

Writing the Markup

What we’ve created here is a simple unordered list of albums with slide-out album controls. You could use something like this to present your band’s albums or to showcase a series of podcasts or any other kind of audio (or potentially video) media. Each item in the list is an album, with some fairly simple markup:

<div class="album">
	<a href=""><img src="/playground/sliding-vinyl/muse-the-resistance.jpg" width="500" height="375" alt="Muse: The Resistance" /></a>
	<span class="vinyl">
		<div></div>
	</span>
	<ul class="actions">
		<li class="play-pause"><a href=""></a></li>
		<li class="info"><a href=""></a></li>
	</ul>
	<div>
		<h5>Muse</h5>
		<small>The Resistance</small>
	</div>
	<span class="gloss"></span>
</div>

It might look like a few extraneous elements are in there, but we’ll be using all of them to render our slide-out record and controller buttons.

Creating the Record

Hotness-4 in The New Hotness: Using CSS3 Visual Effects The real trick here was the album. We challenged ourselves to create the album without using any images at all (we ended up cheating a bit, but we’ll get to that). When it slides out, the album looks like the figure on the left: standard black vinyl with a slight shine to it and a couple of control buttons.

You’ll notice that the inside edge of the album is a little jagged, and that’s because the album isn’t an image but rather two layered gradients generated by the browser and set as the background of the same object. This required not only a bit of messing around with the new gradient objects in CSS3 but also another CSS3 trick: multiple backgrounds. Check out the CSS for the record:

ul.tunes li div.album span.vinyl div {
	display: block;
	border: solid 1px black;
	width: 112px;
	height: 112px;
	-webkit-border-radius: 59px;
	-moz-border-radius: 59px;
	-webkit-box-shadow: 0 0 6px rgba(0,0,0,.5);
	-webkit-transition: all .25s linear;
	background:
		-webkit-gradient(
			linear, left top, left bottom,
			from(transparent),
			color-stop(0.1, transparent),
			color-stop(0.5, rgba(255,255,255,0.25)),
			color-stop(0.9, transparent),
			to(transparent)),
		-webkit-gradient(
			radial, 56 56, 10, 56 56, 112,
			from(transparent),
			color-stop(0.01, transparent),
			color-stop(0.021, rgba(0,0,0,1)),
			color-stop(0.09, rgba(0,0,0,1)),
			color-stop(0.1, rgba(28,28,28,1)),
			to(rgba(28,28,28,1)));
	border-top: 1px solid rgba(255,255,255,.25);
}

We’ve omitted some of the positioning and other boring CSS pieces (check out the live demo for the complete markup). We want to focus here on the pieces that are critical to creating the album visually: border-radius and -webkit-gradient.

The simplest part was creating a round object: by setting the border radius to exactly half of the height and width of the object, the browser masks the object to a perfect circle. Watch out, though: unlike in Photoshop, if the border radius is higher than half the object’s height or width, the browser might simply ignore the declaration. That said, rounding the object is the easy part; the tricky part is controlling the gradients.

Two gradients are at work on the object: one creates the album itself (complete with the hole in the middle), and the other casts a light across it. We’ll start with the shine:

ul.tunes li div.album span.vinyl div {
	...
	background:
		-webkit-gradient(
			linear, left top, left bottom,
			from(transparent),
			color-stop(0.1, transparent),
			color-stop(0.5, rgba(255,255,255,0.25)),
			color-stop(0.9, transparent),
			to(transparent)),
			...
}

The shine gradient is a linear gradient from the top-left to bottom-left. We start with transparent so that the gradient fades in, then we shift the gradient to white at the 50% mark (halfway across the album), with 25% opacity. We’re using RGBa colors because they allow us to control both the color and opacity in the same declaration.

The album itself is more complicated, and it suffers a bit from early implementation of the radial gradient.

ul.tunes li div.album span.vinyl div {
	...
	background:
		...,
		-webkit-gradient(
			radial, 56 56, 10, 56 56, 112,
			from(transparent),
			color-stop(0.01, transparent),
			color-stop(0.021, rgba(0,0,0,1)),
			color-stop(0.09, rgba(0,0,0,1)),
			color-stop(0.1, rgba(28,28,28,1)),
			to(rgba(28,28,28,1)));
	...
}

Radial gradients are just as they sound, and just what you’d expect from gradients in Photoshop. They begin at the center of the object and track across the object in concentric circles. In our case, we wanted to start with transparency, then switch to a solid black, and end up with a very dark gray.

Perhaps the most difficult part of the gradient is declaring its size and position: radial, 56 56, 10, 56 56, 112. We have five pieces of data here: type, starting center, starting diameter, ending center and ending diameter. Here’s how they work:

  • Radial is, of course, where we define this as a circular gradient rather than straight (linear) gradient.
  • We begin at 56 56, which is exactly half the height and width of our 112-pixel-tall object. We want the gradient to end with the same center, so we repeat 56 56.
  • The gradient begins with a diameter of 10 pixel.
  • The ending center (56 56) ensures that this is a concentric gradient.
  • 112 is our final diameter, the same width as the object.

The radial implementation was still a bit rough around the edges, so we played around with these values and the color-stop elements to get the effect we wanted. In the future, a more polished implementation won’t be quite so trial and error.

Hotness-3 in The New Hotness: Using CSS3 Visual Effects From there, similar to the linear gradient, we created a series of color-stops to go from transparent to black to dark gray. The result of these two backgrounds (separated by a comma—thanks, CSS3) is our shiny record. Again, you’ll notice the center is a bit rough, but we’re sure future implementations of this new element will be cleaner.

The button controls are simply rounded anchors (using border-radius), with a couple of image glyphs (we told you we cheated a bit). The final touch was to add the animation so that the album would roll out of the sleeve on hover.

Adding in the Final Animation

To achieve the rolling effect, we paired up a position shift and a rotation effect so that, as the object moves to the right, it rotates just the right amount to appear as if it’s rolling. Here’s what we did:

ul.tunes li div.album span.vinyl {
	-webkit-transition: all .25s linear;
}

ul.tunes li div.album:hover span.vinyl {
	-webkit-transform: translateX(60px);
}

ul.tunes li div.album:hover span.vinyl div {
	-webkit-transform: rotate(120deg);
}

We’re using two transforms, translateX and rotate, on two objects. We use the translate instead of standard positioning because transforms don’t impact the DOM—from a layout perspective, the object never really moves, and so we don’t have to worry about floats going awry or objects pushing each other around. Transitions also work better on translation transforms than on actual position (left: 20px, etc.) changes.

Gradients have a ways to go, but there are already some cool uses for generated gradients. You can even control them at runtime using transitions or JavaScript, which opens up yet more possibilities.

Sliding-vinyl-th in The New Hotness: Using CSS3 Visual Effects

See the Live Demo »

We’ve created a live demo page for this gallery in our Playground, so you can see it in action and delve deeper into the source code. Enjoy!


Sweet Overlays With Border-Image

Hotness-7 in The New Hotness: Using CSS3 Visual Effects

This last part is perhaps the most practical. We use it in our feedback tool Notable every day. The border-image property is new but has some really interesting applications. We’ll explain how it works and how we’re using it in our flagship application.

The Overlay Markup

Overlays in Notable have two parts: the frame and the actual glass overlay. The markup for the overlay is pretty simple, consisting of two sibling DIVs:

<div class="note" id="note1">
	<div class="border"></div>
	<div class="overlay"></div>
	<span class="black circle note">1<span class="wrap"></span></span>
</div>

When we created these overlays, we had a few goals:

  • They shouldn’t overly obscure the content beneath them.
  • They shouldn’t affect the hue of the content beneath them.
  • They must look awesome.

To that end, we devised an overlay that would appear as a glass overlay, with a slight shine and a nice, fairly bold frame. For the purposes of this article, we’ll focus on the frame, which we created using the new border-image property.

Using Border-Image

The new border-image property is a strange beast: very versatile, but takes a little getting used to. Here’s what the border-image declaration for our frame looks like in the CSS:

div.note div.border {
	border: 5px solid #feb515;
	-webkit-border-radius: 3px;
	-moz-border-radius: 3px;
	-webkit-border-image:
		url(/playground/awesome-overlays/border-image.png) 5 5 5 5 stretch;
	-moz-border-image:
		url(/playground/awesome-overlays/border-image.png) 5 5 5 5 stretch;
}

Let’s get the easy stuff out of the way. The border element is both required and a fallback: older browsers will still render a usable border for the overlay, but border-image requires a defined border width. While we’ve been fairly unconcerned with backwards-compatibility in our articles, in this case we needed it (Notable has to work in more than just cutting-edge browsers). This is one of many examples of progressive enhancement (or graceful degradation, if you prefer): older browsers render something usable, just less pretty. The first progressive piece in here is the border-radius, which we’ve already discussed at length.

The border-image is what we’re interested in. Check out the figure to the right; notice the gradient on the frame that goes from top to bottom? It’s a simple touch, but adding it to an object that has to scale to many different sizes required that we use this new property. And we’re glad we did; learning how to use it opened up new possibilities in our coding repertoire. Let’s look at just the border-image code again:

	url(/playground/awesome-overlays/border-image.png) 5 5 5 5 stretch;

The syntax is the same for WebKit and Gecko(Mox) browsers. The actual declaration is simple. What takes some effort is understanding how to create the image file itself.

Border image takes a single image and slices it into nine pieces, which it then stretches over the object. We’ve sketched a diagram to explain how this works, and we’ve blown up the actual border image file for you to compare. Check it out:

Hotness-5 in The New Hotness: Using CSS3 Visual Effects

The browser takes the top-left corner and uses it for the top-left border, and then it stretches the top-middle to cover the entire top of the object, and so on around the image.

Hotness-6 in The New Hotness: Using CSS3 Visual Effects

We created an image with transparent center, because border-image will stretch the center quadrant across the entire object (which seems counterintuitive for a “border” image, but it does make the style a bit more versatile). You’ll notice that the actual gradient is present only in quadrants 4 and 6, because those are the only pieces that will be stretched enough for us to see a gradient. The browser actually does a good job of stretching the image as long as it’s not too complex, so artifacts aren’t really an issue.

The last pieces of the border-image declaration are the size and style: 5 5 5 5 stretch. The repeated 5s determine the size on each side of the object; because we wanted a 5-pixel border, we created an image that was 15 x 15. If we had used a smaller image, the browser would have had to scale the corners as well, and no doubt it would have looked messier. The last property, stretch, dictates how the browser actually handles the pieces of the image. A great (and amusing) intro to the different styles can be found at lrbabe.

Putting It Together

Combining the frame with the glass overlay center (which is a semi-transparent PNG) gives us our frame. Using different border images, we actually created classes for our different colors (red, blue, etc.), while older browsers still get a usable frame without the gradient-edged niceties. This isn’t an incredibly complex example, but you can see how useful border-image can be, especially using an alpha-mapped image format such as PNG.

Awesome-overlays-th in The New Hotness: Using CSS3 Visual Effects

See the Live Demo »

We’ve created a live demo page for this gallery in our Playground so that you can see it in action and delve deeper into the source code. You can also read up on why we created this overlay in our two-part Notable Behind the Scenes blog post: part 1 and part 2.


CSS 3 Is Totally Bad Ass

Right? We hope you’ve enjoyed this primer on what we can look forward to in the final CSS3 specification. Familiarize yourself with the properties and start using them—just be sure to account for browsers that, sadly, will never support all of these fun new tricks. You can see how we use CSS3 in our work for clients as well as in our own product, Notable. Found a super-awesome way to use these new properties? We’d love to hear about it in the comments!

References and Resources

(al)


© ZURB for Smashing Magazine, 2010. | Permalink | 106 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: ,

Tags: