Archive for April, 2010

CSS3 Solutions for Internet Explorer

POSTED IN Blog | Comments Off

CSS3 is probably the hottest trend in web design right now, allowing developers the opportunity to implement a number of solutions into their projects with some very straightforward CSS while avoiding having to resort to nonsemantic markup, extra images, and complex JavaScript. Unfortunately, it’s not a surprise that Internet Explorer, even in its most recent version, still does not support the majority of the properties and features introduced in CSS3.

Experienced developers understand that CSS3 can be added to new projects with progressive enhancement in mind. This ensures that content is accessible while non-supportive browsers fall back to a less-enhanced experience for the user.

Ie in CSS3 Solutions for Internet Explorer

But developers could face a situation where a client insists that the enhancements work cross-browser, demanding support even for IE6. In that case, I’ve collected together a number of options that developers can consider for those circumstances where support for a CSS3 feature is required for all versions of Internet Explorer (IE6, IE7, & IE8 — all of which are still currently in significant use).

[Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #1 is Professional Web Design, 242 pages for just $9,90.]

Opacity / Transparency

I think all developers are baffled at why Internet Explorer still fails to support this very popular (albeit troublesome) property. It’s been around so long, that we often forget that it’s actually a CSS3 property. Although IE doesn’t offer support for the opacity property, it does offer similar transparency settings via the proprietary filter property:

The Syntax

#myElement {
	opacity: .4; /* other browsers */
	filter: progid:DXImageTransform.Microsoft.Alpha(opacity=40); /* this works in IE6, IE7, and IE8 */
	-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=40)"; /* this works in IE8 only */
}

You really only need the second line, which works in all three versions of Internet Explorer. But if for some reason you needed the opacity setting to apply only to IE8, and not to IE6/7, then you can use the third line, which the older versions don’t recognize.

The opacity value at the end of each IE line works basically the same way that the opacity property does, taking a number from 0 to 100 (the opacity property takes a two-digit number from 0 to 1, so “44″ for IE would be “0.44″ for the others). Also, as many have experienced when using opacity (even when using the standard method), the opacity settings will be inherited by all child elements, for which there is no easy workaround.

The Demonstration

This element has a solid blue background color (#0000FF), but is 60% transparent, making it appear light blue in all browsers

This is the same element without the opacity settings.

The Drawbacks

  • The filter property is a Microsoft-only property, so your CSS won’t validate
  • As is the case for the opacity property, the IE filter causes all child elements to inherit the opacity

Rounded Corners (border-radius)

The border-radius property (more commonly referred to as CSS3 rounded corners) is another popular CSS3 enhancement. This property has allowed developers to avoid the headache of bloated JavaScript or extra positioned elements to achieve the same effect. But once again, Microsoft doesn’t want to cooperate, so IE doesn’t have any support for this property.

Fortunately, at least one person has come up with a very usable workaround that can be used in an IE-only stylesheet. Remiz Rahnas of HTML Remix has created an HTC file called CSS Curved Corner that can be downloaded off Google Code.

The great thing about this piece of code is that it doesn’t require any extra maintenance if you adjust the amount of radius on your rounded corners. You just link to the file in your CSS, and the script will automatically parse your CSS to find the correct radius value from the standard border-radius property.

The Syntax

Here’s what your code might look like:

.box-radius {
	border-radius: 15px;
	behavior: url(border-radius.htc);
}

The way it works is pretty straightforward, as shown above. Ideally, however, you would apply the behavior property in an IE-only stylesheet, using the same selector in your CSS, so the code knows where to get the radius value from.

The Demonstration

Because this technique requires use of an external HTC file, you can view the demo at this location.

The Drawbacks

  • The HTC file is 142 lines (minifying or GZipping would help, but it’s still extra bloat)
  • The behavior property will make your CSS invalid
  • Your server needs to be able to load HTC files for this technique to work
  • IE8 seems to have some trouble in some circumstances when the HTC file forces the curved element to have a negative z-index value

Box Shadow

The box-shadow property is another useful CSS3 feature that will even add a curved box shadow naturally to an element that uses the border-radius property. IE doesn’t support box-shadow, but a filter is available that offers a close replication.

It should be noted that the box-shadow property has been removed from the CSS3 Backgrounds and Borders Module, so its future in CSS3 seems to be a little uncertain right now.

The Syntax

.box-shadow {
	-moz-box-shadow: 2px 2px 3px #969696; /* for Firefox 3.5+ */
	-webkit-box-shadow: 2px 2px 3px #969696; /* for Safari and Chrome */
	filter: progid:DXImageTransform.Microsoft.Shadow(color='#969696', Direction=145, Strength=3);
}

As shown above, in addition to the proprietary WebKit and Mozilla properties, you can add a shadow filter that works in all versions of Internet Explorer.

The Demonstration

This element has a drop shadow that works in Internet Explorer.

The Drawbacks

  • The settings for the IE shadow filter do not match those of the other proprietary properties, so in order to make it look the same, you have to fiddle with the values until you get it right, which can cause maintenance headaches
  • The filter property doesn’t validate, but neither do the WebKit and Mozilla properties, so this is a drawback in all browsers

Text Shadow

Adding drop shadows to text elements has been practiced in both print and web design for years. On the web, this is normally done with images and occasionally with text duplication combined with positioning. CSS3 allows developers to easily add shadows to text using a simple and flexible text-shadow property.

Unfortunately, there doesn’t seem to be an easy way to add a text shadow in Internet Explorer — even with the use of proprietary filters. To deal with this problem, a Dutch front-end developer named Kilian Valkhof has written a jQuery plugin that implements text shadows in Internet Explorer.

The Syntax

First, in your CSS, you would set the text-shadow property:

.text-shadow {
	text-shadow: #aaa 1px 1px 1px;
}

The values specify the shadow color, position on the horizontal axis, position on the vertical axis, and the amount of blur.

After including the jQuery library and the plugin in your document, you can call the plugin with jQuery:

// include jQuery library in your page
// include link to plugin in your page

$(document).ready(function(){
	$(".text-shadow").textShadow();
});

The plugin also allows the use of parameters to override the CSS. See the plugin author’s original web page for more details on the parameters.

Although there is a cross-browser jQuery plugin that applies drop shadows, the one I’m demonstrating above actually utilizes the CSS3 value that’s already set in your CSS, so it has the advantage of working along with the standard CSS setting for text shadows, whereas the other plugin needs to be set independently.

The Demonstration

Because this technique requires use of the jQuery library and an external plugin file, you can view the demo at this location.

The Drawbacks

There are some significant drawbacks to this method that make it very unlikely to ever be practical. You’re probably better off creating an image to replace the text for IE instead.

  • In order to make the shadow look almost the same in IE, you need to use different settings in an IE-only stylesheet, adding to development and maintenance time
  • Requires that you add the jQuery library, in addition to a 61-line plugin file (GZipping or minifying would help)
  • The IE version of the shadow never looks exactly the same as the other browsers
  • When using the overriding parameters, the plugin seems to be rendered somewhat useless, displaying a big ugly shadow that won’t change with new values
  • Unlike the CSS3 version, the plugin doesn’t support multiple shadows
  • For some reason, in order to get it to work in IE8, you need to give the element a z-index value

Gradients

Another practical and time-saving technique introduced in CSS3 is the ability to create custom gradients as backgrounds. Although Internet Explorer doesn’t support gradients of the CSS3 variety, it’s pretty easy to implement them for the IE family using proprietary syntax.

The Syntax

To declare a gradient that looks the same in all browsers, including all versions of Internet Explorer, use the CSS shown below (the last two lines are for IE):

#gradient {
	background-image: -moz-linear-gradient(top, #81a8cb, #4477a1); /* Firefox 3.6 */
	background-image: -webkit-gradient(linear,left bottom,left top,color-stop(0, #4477a1),color-stop(1, #81a8cb)); /* Safari & Chrome */
	filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#81a8cb', endColorstr='#4477a1'); /* IE6 & IE7 */
	-ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#81a8cb', endColorstr='#4477a1')"; /* IE8 */
}

For the IE filters, the GradientType can be set to “1″ (horizontal) or “0″ (vertical).

The Demonstration

This element has a linear gradient that works in Internet Explorer.

The Drawbacks

Some of the usual drawbacks apply to gradients created with the IE-only filter, along with some other problems.

  • Your CSS won’t validate, although that’s also true for the WebKit and Mozilla values
  • Different code is needed for IE8, adding to maintenance time
  • The WebKit and Mozilla gradients allow for “stops” to be declared; this doesn’t seem to be possible with the IE gradient, limiting its flexibility
  • IE’s filter doesn’t seem to have a way to declare “radial” gradients, which WebKit and Mozilla support
  • For a gradient to be visible in IE, the element with the gradient must have layout

Transparent Background Colors (RGBA)

CSS3 offers another method to implement transparency, doing so through an alpha channel that’s specified on a background color. Internet Explorer offers no support for this, but this can be worked around.

The Syntax

For the CSS3-compliant browsers, here’s the syntax to set an alpha channel on the background of an element:

#rgba p {
	background: rgba(98, 135, 167, .4);
}

With the above CSS, the background color will be set to the RGB values shown, plus the optional “alpha” value of “.4″. To mimic this in Internet Explorer, you can use the proprietary filter property to create a gradient with the same start and end color, along with an alpha transparency value. This would be included in an IE-only stylesheet, which would override the previous setting.

#rgba p {
	filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#886287a7', endColorstr='#886287a7');
}

The “gradient” will look exactly the same in IE as in other browsers, duplicating the RGBA transparency effect.

The Demonstration

This first example below will work in browsers that support RGBA colors. The second example will only work in Internet Explorer.

This paragraph has a background color with a 40% opacity setting declared using RGBA (doesn’t work in IE).

This paragraph has an IE-only filter applied to mimic RGBA transparency (only works in IE).

The Drawbacks

  • The filter property is not valid CSS
  • Requires an extra line of CSS in an IE-only stylesheet
  • The element needs to have layout

Note: Initially, I had used a PNG image method to achieve this effect, but apparently it was working only partially in IE7 and IE8, and required a PNG-hack for IE6, so I tried the method given by Liam and Matias in the comments and this seems to work better. The PNG method is another option, but seems to be more troublesome, and has more drawbacks.

Multiple Backgrounds

This is another CSS3 technique that, when widely supported, could prove to be a very practical addition to CSS development. Currently, IE and Opera are the only browsers that don’t support this feature. But interestingly, IE as far back as version 5.5 has allowed the ability to implement multiple backgrounds on the same element using a filter.

The Syntax

You might recall trying to hack a PNG in IE6 and noticing the image you were trying to hack appearing twice, which you had to remove by adding background: none, then applying the filter. Well, using the same principle, IE allows two background images to be declared on the same element.

To use multiple backgrounds in Firefox, Safari, and Chrome, here’s the CSS:

#multi-bg {
	background: url(images/bg-image-1.gif) center center no-repeat, url(images/bg-image-2.gif) top left repeat;
}

To apply two backgrounds to the same element in IE, use the following in an IE-only stylesheet:

#multi-bg {
	background: transparent url(images/bg-image-1.gif) top left repeat;
	filter: progid:DXImageTransform.Microsoft.AlphaImageLoader (src='images/bg-image-2.gif', sizingMethod='crop'); /* IE6-8 */
	-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/bg-image-2.gif', sizingMethod='crop')"; /* IE8 only */
}

The Demonstration

The box below shows multiple backgrounds in Chrome, Firefox, and Safari (you won’t see anything in IE):

The next box shows multiple backgrounds in Internet Explorer 6-8 (you’ll only see a single background in other browsers):

The Drawbacks

  • Your CSS will be invalid
  • The second background image applied using the filter property will always be in the top left, and cannot repeat, so this method is extremely inflexible and can probably only be used in a limited number of circumstances
  • In order to get the element to center (as in other browsers), you have to create an image with the exact amount of whitespace around it, to mimic the centering, as I’ve done in the demonstration above
  • The AlphaImageLoader filter causes performance issues, as outlined here

Element Rotation (CSS Tranformations)

CSS3 has introduced a number of transformation and animation capabilities, which some have suggested are out of place in CSS. Nonetheless, there is a way to mimic element rotation in Internet Explorer, albeit in a limited fashion.

The Syntax

To rotate an element 180 degrees (that is, to flip it vertically), here is the CSS3 syntax:

#rotate {
	-webkit-transform: rotate(180deg);
	-moz-transform: rotate(180deg);
}

To create the exact same rotation in Internet Explorer, you use a proprietary filter:

#rotate {
	filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2);
}

The value for the rotation can be either 1, 2, 3, or 4. Those numbers represent 90, 180, 270, or 360 degrees of rotation respectively.

The Demonstration

The element below should appear upside down in Internet Explorer, having a rotation of 180 degrees set via the filter property. To demonstrate this more emphatically, I’ve applied a 3px solid gray “bottom” border, which should appear at the top of the element.

This element is rotated 180 degrees in Internet Explorer.

The Drawbacks

  • Your CSS won’t validate, although that’s also true for the WebKit and Mozilla code
  • While the Mozilla and WebKit code allows for rotation changes to increment by a single degree, the IE filter only permits 4 stages of rotation, minimizing its flexibility

Update: As pointed out in the comments, IE does allow the ability to rotate objects with the same flexibility as the CSS3 methods. To explain the method here is too complex, but the CSS3, please project by Paul Irish has implemented this method into its code generator, so you can use that to create the IE-compatible code for CSS3 rotations.

Conclusion

Developers might hate me for compiling this list, seeing as any client could search for “CSS3 in Internet Explorer” and stumble across this page. So be careful what you tell your clients; although IE does not support these things natively, that doesn’t mean they’re impossible to implement.

And remember that anytime you need to override the initial CSS settings for IE, or if you have to use JavaScript, jQuery, or an HTC file, make sure the calls to the external resources are made using IE conditional comments. This will ensure the other browsers aren’t making unnecessary HTTP requests.

In many cases, the best solution for dealing with Internet Explorer is to let it display a less-enhanced experience. I hope, however, the above solutions provide some options for working with CSS3 when a client wants a more accurate cross-browser experience.

Related Posts

You may be interested in the following related posts:


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

Five Tips For Making Ideas Happen

POSTED IN Blog | Comments Off

Smashing-magazine-advertisement in Five Tips For Making Ideas Happen
 in Five Tips For Making Ideas Happen  in Five Tips For Making Ideas Happen  in Five Tips For Making Ideas Happen

Creative types have a problem. We have so many great ideas, but most of them never see the light of day. Why do most ideas never happen? The reason is that our own creative habits get in the way. For example, our tendency to generate new ideas often gets in the way of executing the ones we have. As a result, we abandon many projects halfway through. Whether a personal website, a new business idea or a long-dreamt novel, most of these projects stagnate and become a source of frustration.

Some creative people and teams are able to defy the odds and make their ideas happen, time and again. In my work, I have spent the better part of five years meeting these exceptional people and chronicling their habits and insight, which has resulted in the following tips and suggestions for making ideas happen.

[Offtopic: by the way, did you know that Smashing Magazine has one of the most influential and popular Twitter accounts? Join our discussions and get updates about useful tools and resources — follow us on Twitter!]

1. Avoid A Reactionary Workflow

Workflow1 in Five Tips For Making Ideas Happen

Without realizing it, most of us have gradually adopted a “reactionary workflow.” We are constantly bombarded with incoming communication: email, text messages, tweets, Facebook posts, phone calls, instant messages, etc. Rather than be proactive with our energy, we spend all of our energy reacting, enslaved to the last incoming item.

To avoid this reactionary workflow, some of the most productive people I have met schedule what can be called “windows of non-stimulation” in their day. For two to three hours per day, these people avoid email and all other incoming communication. In this time, they focus on their list of big items: not routine tasks, but long-term projects that require research and deep thought.

Another idea is to aggregate all messages in a central location. Setting your social networks to email you, and using filters to automatically manage these emails, will reduce your “hopping time” (when you hop between sources of communication) and focus your attention. Some people even have their voice mails transcribed automatically and forwarded by email. In a world of many inboxes, you have to consolidate.

2. Strip Projects To Three Primary Elements

Breakdown in Five Tips For Making Ideas Happen

Every project in life can ultimately be reduced to just three primary elements: 1) action steps, 2) backburner items and 3) references. Action steps are tasks that can be articulated succinctly and begin with verbs. They should be kept separate from your notes and sketches.

Backburner items are ideas that come up during brainstorming or while on the run and that are not actionable but may be later on. Backburner items should be collected in a central location and revisited periodically as a ritual. One leader I met prints out his list of backburner items (which he stores in Word document) on the first Sunday of every month. He grabs the sheet (and a beer) and then sits down to review the entire list. Some items will be crossed off as irrelevant, some will remain on the list, and some will be transformed into action steps.

The third element of every project is references: the articles, notes and other stuff that collect around you. It turns out that references are overrated. Rather than spend hours organizing your notes, consider simply filing your notes chronologically (i.e. not by project or anything else) in one big file. In the age of digital calendars, we can search for any meeting and quickly find the notes taken on that date.

3. Measure Meetings With Action Steps

Meeting in Five Tips For Making Ideas Happen

Meetings are extremely expensive considering the cost of time and interruptions they represent. Beware of “posting meetings” or meeting “just because it’s Monday.” Such meetings are usually scheduled for the morning—when you’re at your most productive—and often end without any action steps having been captured. A meeting that ends without any action steps should have been a voice mail or email.

When you do meet with clients or colleagues, end each meeting with a quick review and capture the action steps. The exercise should take less than 30 seconds per person. Each person should share what they captured. Doing so will almost always reveal a few action steps that were missed, duplicated or misunderstood. Reading your action steps aloud also cultivates a sense of accountability.

4. Reduce Your Insecurity Work

Insecurity in Five Tips For Making Ideas Happen

In the era of Google Analytics and Twitter, we spend too much time obsessing over real-time data because it’s all at our fingertips. Whether it’s your website’s traffic or bank account, checking these repeatedly doesn’t help make your ideas happen. They just make you feel “safe.” Insecurity work is stuff we do that (1) has no definable outcome, (2) does not move the ball forward in any way and (3) takes up so little time that we can do it multiple times a day without realizing it. Still, it puts us at ease.

The first step to reducing insecurity work is becoming self-aware. Identify the insecurity work in your daily life. The second step is to establish guidelines and rituals for yourself that create discipline. Perhaps you could try restricting all of your insecurity work to a particular 30 minutes every day? The third step, if applicable, is to delegate your insecurity tasks to a less insecure colleague, who can review the data periodically and report any concerns.

5. The Creative Process Is About Surviving The “Project Plateau.”

Plateau in Five Tips For Making Ideas Happen

Everyone has their own approach to generating ideas. There’s no “best way” to be creative. But when it comes to the process of executing ideas, we all face one challenge in particular: sticking with it. Most ideas are abandoned at what I’ve come to call the “project plateau”: the point when creative excitement wanes and the pain of deadlines and project management becomes burdensome. To escape this pain, we generate a new idea (and abandon the one we were working on). This process can easily repeat itself ad infinitum, without us ever finishing anything meaningful.

Show your ideas some respect, and spend some energy improving how you execute. If not for you, do it for everyone else who will benefit from your ideas once they actually see the light.

(al)


© Scott Belsky 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:

Smashing-magazine-advertisement in Seven JavaScript Things I Wish I Knew Much Earlier In My Career
 in Seven JavaScript Things I Wish I Knew Much Earlier In My Career  in Seven JavaScript Things I Wish I Knew Much Earlier In My Career  in Seven JavaScript Things I Wish I Knew Much Earlier In My Career

I’ve been writing JavaScript code for much longer than I care to remember. I am very excited about the language’s recent success; it’s good to be a part of that success story. I’ve written dozens of articles, book chapters and one full book on the matter, and yet I keep finding new things. Here are some of the “aha!” moments I’ve had in the past, which you can try out rather than waiting for them to come to you by chance.

[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.]

Shortcut Notations

One of the things I love most about JavaScript now is shortcut notations to generate objects and arrays. So, in the past when we wanted to create an object, we wrote:

var car = new Object();
car.colour = 'red';
car.wheels = 4;
car.hubcaps = 'spinning';
car.age = 4;

The same can be achieved with:

var car = {
  colour:'red',
  wheels:4,
  hubcaps:'spinning',
  age:4
}

Much shorter, and you don’t need to repeat the name of the object. Right now, car is fine, but what happens when you use invalidUserInSession? The main gotcha in this notation is IE. Never ever leave a trailing comma before the closing curly brace or you’ll be in trouble.

The other handy shortcut notation is for arrays. The old school way of defining arrays was this:

var moviesThatNeedBetterWriters = new Array(
  'Transformers','Transformers2','Avatar','Indiana Jones 4'
);

The shorter version of this is:

var moviesThatNeedBetterWriters = [
  'Transformers','Transformers2','Avatar','Indiana Jones 4'
];

The other thing about arrays is that there is no such thing as an associative array. You will find a lot of code examples that define the above car example like so:

var car = new Array();
car['colour'] = 'red';
car['wheels'] = 4;
car['hubcaps'] = 'spinning';
car['age'] = 4;

This is not Sparta; this is madness—don’t bother with this. “Associative arrays” is a confusing name for objects.

Another very cool shortcut notation is the ternary notation for conditions. So, instead of the following…

var direction;
if(x < 200){
  direction = 1;
} else {
  direction = -1;
}

… You could write a shorter version using the ternary notation:

var direction = x < 200 ? 1 : -1;

The true case of the condition is after the question mark, and the other case follows the colon.

JSON As A Data Format

Before I discovered JSON to store data, I did all kinds of crazy things to put content in a JavaScript-ready format: arrays, strings with control characters to split, and other abominations. The creation of JSON by Douglas Crockford changed all that. Using JSON, you can store complex data in a format that is native to JavaScript and doesn't need any extra conversion to be used immediately.

JSON is short for "JavaScript Object Notation" and uses both of the shortcuts we covered earlier.

So, if I wanted to describe a band, for example, I could do the following:

var band = {
  "name":"The Red Hot Chili Peppers",
  "members":[
    {
      "name":"Anthony Kiedis",
      "role":"lead vocals"
    },
    {
      "name":"Michael 'Flea' Balzary",
      "role":"bass guitar, trumpet, backing vocals"
    },
    {
      "name":"Chad Smith",
      "role":"drums,percussion"
    },
    {
      "name":"John Frusciante",
      "role":"Lead Guitar"
    }
  ],
  "year":"2009"
}

You can use JSON directly in JavaScript and, when wrapped in a function call, even as a return format of APIs. This is called JSON-P and is supported by a lot of APIs out there. You can use a data endpoint, returning JSON-P directly in a script node:

<div id="delicious"></div><script>
function delicious(o){
  var out = '<ul>';
  for(var i=0;i<o.length;i++){
    out += '<li><a href="' + o[i].u + '">' +
           o[i].d + '</a></li>';
  }
  out += '</ul>';
  document.getElementById('delicious').innerHTML = out;
}
</script>
<script src="http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious"></script>

This calls the Delicious Web service to get my latest JavaScript bookmarks in JSON format and then displays them as an unordered list.

In essence, JSON is probably the most lightweight way of describing complex data—and it runs in a browser. You can even use it in PHP using the json_decode() function.

Native JavaScript Functions (Math, Array And String)

One thing that amazed me is how much easier my life got once I read up thoroughly on the math and string functions of JavaScript. You can use these to avoid a lot of looping and conditions. For example, when I had the task of finding the largest number in an array of numbers, I used to write a loop, like so:

var numbers = [3,342,23,22,124];
var max = 0;
for(var i=0;i<numbers.length;i++){
  if(numbers[i] > max){
    max = numbers[i];
  }
}
alert(max);

This can be achieved without a loop:

var numbers = [3,342,23,22,124];
numbers.sort(function(a,b){return b - a});
alert(numbers[0]);

Notice that you cannot use sort() on a number array because it sorts lexically. There's a good tutorial on sort() here in case you need to know more.

Another interesting method is Math.max(). This one returns the largest number from a list of parameters:

Math.max(12,123,3,2,433,4); // returns 433

Because this tests for numbers and returns the largest one, you can use it to test for browser support of certain properties:

var scrollTop= Math.max(
 doc.documentElement.scrollTop,
 doc.body.scrollTop
);

This works around an Internet Explorer problem. You can read out the scrollTop of the current document, but depending on the DOCTYPE of the document, one or the other property is assigned the value. When you use Math.max() you get the right number because only one of the properties returns one; the other will be undefined. You can read more about shortening JavaScript with math functions here.

Other very powerful functions to manipulate strings are split() and join(). Probably the most powerful example of this is writing a function to attach CSS classes to elements.

The thing is, when you add a class to a DOM element, you want to add it either as the first class or to already existing classes with a space in front of it. When you remove classes, you also need to remove the spaces (which was much more important in the past when some browsers failed to apply classes with trailing spaces).

So, the original function would be something like:

function addclass(elm,newclass){
  var c = elm.className;
  elm.className = (c === '') ? newclass : c+' '+newclass;
}

You can automate this using the split() and join() methods:

function addclass(elm,newclass){
  var classes = elm.className.split(' ');
  classes.push(newclass);
  elm.className = classes.join(' ');
}

This automatically ensures that classes are space-separated and that yours gets tacked on at the end.

Event Delegation

Events make Web apps work. I love events, especially custom events, which make your products extensible without your needing to touch the core code. The main problem (and actually one of its strengths) is that events are removed from the HTML—you apply an event listener to a certain element and then it becomes active. Nothing in the HTML indicates that this is the case though. Take this abstraction issue (which is hard for beginners to wrap their heads around) and the fact that "browsers" such as IE6 have all kind of memory problems and too many events applied to them, and you'll see that not using too many event handlers in a document is wise.

This is where event delegation comes in. When an event happens on a certain element and on all the elements above it in the DOM hierarchy, you can simplify your event handling by using a single handler on a parent element, rather than using a lot of handlers.

What do I mean by that? Say you want a list of links, and you want to call a function rather than load the links. The HTML would be:

<h2>Great Web resources</h2>
<ul id="resources">
  <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>
  <li><a href="http://sitepoint.com">Sitepoint</a></li>
  <li><a href="http://alistapart.com">A List Apart</a></li>
  <li><a href="http://yuiblog.com">YUI Blog</a></li>
  <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>
  <li><a href="http://oddlyspecific.com">Oddly specific</a></li>
</ul>

The normal way to apply event handlers here would be to loop through the links:

// Classic event handling example
(function(){
  var resources = document.getElementById('resources');
  var links = resources.getElementsByTagName('a');
  var all = links.length;
  for(var i=0;i<all;i++){
    // Attach a listener to each link
    links[i].addEventListener('click',handler,false);
  };
  function handler(e){
    var x = e.target; // Get the link that was clicked
    alert(x);
    e.preventDefault();
  };
})();

This could also be done with a single event handler:

(function(){
  var resources = document.getElementById('resources');
  resources.addEventListener('click',handler,false);
  function handler(e){
    var x = e.target; // get the link tha
    if(x.nodeName.toLowerCase() === 'a'){
      alert('Event delegation:' + x);
      e.preventDefault();
    }
  };
})();

Because the click happens on all the elements in the list, all you need to do is compare the nodeName to the right element that you want to react to the event.

Disclaimer: while both of the event examples above work in browsers, they fail in IE6. For IE6, you need to apply an event model other than the W3C one, and this is why we use libraries for these tricks.

The benefits of this approach are more than just being able to use a single event handler. Say, for example, you want to add more links dynamically to this list. With event delegation, there is no need to change anything; with simple event handling, you would have to reassign handlers and re-loop the list.

Anonymous Functions And The Module Pattern

One of the most annoying things about JavaScript is that it has no scope for variables. Any variable, function, array or object you define that is not inside another function is global, which means that other scripts on the same page can access—and will usually override— them.

The workaround is to encapsulate your variables in an anonymous function and call that function immediately after you define it. For example, the following definition would result in three global variables and two global functions:

var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
  // [...]
}
function getMemberDetails(){
  // [...]
}

Any other script on the page that has a variable named status could cause trouble. If we wrap all of this in a name such as myApplication, then we work around that issue:

var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
}();

This, however, doesn't do anything outside of that function. If this is what you need, then great. You may as well discard the name then:

(function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
})();

If you need to make some of the things reachable to the outside, then you need to change this. In order to reach createMember() or getMemberDetails(), you need to return them to the outside world to make them properties of myApplication:

var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  return{
    createMember:function(){
      // [...]
    },
    getMemberDetails:function(){
      // [...]
    }
  }
}();
// myApplication.createMember() and
// myApplication.getMemberDetails() now works.

This is called a module pattern or singleton. It was mentioned a lot by Douglas Crockford and is used very much in the Yahoo User Interface Library YUI. What ails me about this is that I need to switch syntaxes to make functions or variables available to the outside world. Furthermore, if I want to call one method from another, I have to call it preceded by the myApplication name. So instead, I prefer simply to return pointers to the elements that I want to make public. This even allows me to shorten the names for outside use:

var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
  return{
    create:createMember,
    get:getMemberDetails
  }
}();
//myApplication.get() and myApplication.create() now work.

I've called this "revealing module pattern."

Allowing For Configuration

Whenever I've written JavaScript and given it to the world, people have changed it, usually when they wanted it to do things that it couldn't do out of the box—but also often because I made it too hard for people to change things.

The workaround is to add configuration objects to your scripts. I've written about JavaScript configuration objects in detail, but here's the gist:

  • Have an object as part of your whole script called configuration.
  • In it, store all of the things that people will likely change when they use your script:
    • CSS ID and class names;
    • Strings (such as labels) for generated buttons;
    • Values such as "number of images being displayed," "dimensions of map";
    • Location, locale and language settings.
  • Return the object as a public property so that people can override it.

Most of the time you can do this as a last step in the coding process. I've put together an example in "Five things to do to a script before handing it over to the next developer."

In essence, you want to make it easy for people to use your code and alter it to their needs. If you do that, you are much less likely to get confusing emails from people who complain about your scripts and refer to changes that someone else actually did.

Interacting With The Back End

One of the main things I learned from all my years with JavaScript is that it is a great language with which to make interactive interfaces, but when it comes to crunching numbers and accessing data sources, it can be daunting.

Originally, I learned JavaScript to replace Perl because I was sick of copying things to a cgi-bin folder in order to make it work. Later on, I learned that making a back-end language do the main data churning for me, instead of trying to do all in JavaScript, makes more sense with regard to security and language.

If I access a Web service, I could get JSON-P as the returned format and do a lot of data conversion on the client, but why should I when I have a server that has a richer way of converting data and that can return the data as JSON or HTML… and cache it for me to boot?

So, if you want to use AJAX, learn about HTTP and about writing your own caching and conversion proxy. You will save a lot of time and nerves in the long run.

Browser-Specific Code Is A Waste Of Time. Use Libraries!

When I started Web development, the battle between using document.all and using document.layers as the main way to access the document was still raging. I chose document.layers because I liked the idea of any layer being its own document (and I had written more than enough document.write solutions to last a lifetime). The layer model failed, but so did document.all. When Netscape 6 went all out supporting only the W3C DOM model, I loved it, but end users didn't care. End users just saw that this browser didn't show the majority of the Internets correctly (although it did)—the code we produced was what was wrong. We built short-sighted code that supported a state-of-the-art environment, and the funny thing about the state of the art is that it is constantly changing.

I've wasted quite some time learning the ins and outs of all of the browsers and working around their issues. Doing this back then secured my career and ensured that I had a great job. But we shouldn't have to go through this trial by fire any longer.

Libraries such as YUI, jQuery and Dojo are here to help us with this. They take on the problems of browsers by abstracting the pains of poor implementation, inconsistencies and flat-out bugs, and relieve us of the chore. Unless you want to beta test a certain browser because you're a big fan, don't fix browser issues in your JavaScript solutions, because you are unlikely to ever update the code to remove this fix. All you would be doing is adding to the already massive pile of outdated code on the Web.

That said, relying solely on libraries for your core skill is short-sighted. Read up on JavaScript, watch some good videos and tutorials on it, and understand the language. (Tip: closures are God's gift to the JavaScript developer.) Libraries will help you build things quickly, but if you assign a lot of events and effects and need to add a class to every HTML element in the document, then you are doing it wrong.

Resources

In addition to the resources mentioned in this article, also check out the following to learn more about JavaScript itself:

Related Posts

You may be interested in the following related posts:

(al)


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

Typeface. Oh, what can I say about typeface. It is much abused and rarely understood. What happens to people when they pull down that font menu? I think they see a box full of unique and dazzling treasures, and then get blinded by the sparkle of promise that each one holds. The continually type written world has lost the art of penmanship almost entirely and even puts phone calls on the back burner when a quick e-mail will successfully avoid all the chit chat. Now, I’m not saying these things are bad, I mean I love e-mail as much as the next girl, but there is something about that beautifully handwritten letter (which seems, now, to only come from my grandmother) that seems to have so much personality. And this brings me to comic sans. I don’t know how it gets translated this way, but people see comic sans and think –that’s my handwriting. Do we all think we write like 3rd graders? Actually, I think people mistakenly see it as innocent and casual. More than a failed attempt to capture the personality of our own handwriting, I think it is truly a matter of us believing that the tone of our e-mails are misheard by their readers. So, we feel as though we have to use a font that will take the edge off, if you will, of our short, to the point sentences. Our other typeface mishaps seem to come when we try and pair a font with a specific theme. Everyone loves that font whose letters are nested inside cute little ornaments. It’s hard to read with all those circles, but it definitely says Christmas. Then we find ourselves thinking– when will I ever get the chance to use this font again? I find myself feeling sorry for these types of fonts because they seem so fit for the occasion, but in execution they tend to look–well, cheap. Most often our goal is not to look cliché or cute, but to convey to our audience (be they friends or coworkers) a mood. More often than not when it comes to typeface the untrained often fail and end up annoying their audience with 16 pt red comic sans in every e-mail. So, to prevent you from being labeled the “crazy comic sans” lady (or guy) here are a few things to ponder.


1. The most important thing in your e-mail is the information you are giving the reader.

No, comic sans does not look like your handwriting, and everyone uses it so it’s certainly not unique to you. Don’t let your typeface (or the color of) talk louder than your e-mail. It is distracting (some would say annoying) to get an e-mail full of smileys or an unusual typeface.


2. With typeface, the devil is in the details.

Serifs being one. Serifs are those little kick outs at the top and bottom of the letters that look like little feet. Fonts without serifs (sans serif) don’t have the little feet and are considered less formal than serif fonts. Serif fonts, however, are easier to read in blocks of text (like books or magazines) because they keep your eye on the line you are reading. A sans serif typeface will lead your eye down the page instead of across because it has no little feet to kick your eye back up to the next word. That being said it doesn’t mean that sans serif should never be used for blocks of text, it’s just a general rule. Don’t go crazy with fonts that have cutesy little curly serifs or large distracting ones.

3. Subtlety is key

When you open your magical box of treasures take a look at those “boring” fonts that you aren’t drawn to. Those are your best bet! I know, it’s hard not to pick Curls because it’s so darn cute and you have a girly personality or you’re having a tea pary, but you could pick a nice serif font that has a bit fatter letter, or one where the stems of the letters are thicker on one side and thinner on the other. These will look equally feminine and be less cliché.

4. But Comic Sans, Curls, Copperplate… is So cute! I know, but resist the temptation to type completely in these fonts.

You can use them, however, in moderation. If you find an appropriate opportunity to use these fonts you may, but only use them as part of the heading. Pick another typeface that is “boring” to go with it for the body of the document.

5. Don’t type in all caps all the time.

All caps (even if it’s a caps and small caps font) means you’re YELLING. Always. So does red. Don’t type your e-mails in red, or pink. E-mails should be in black unless you are a teenage girl, then you have permission to type e-mails in pink or any other color you like. If you are a grown up–don’t.

So, if you want it to look like your handwriting, then write it by hand. Otherwise, choose a font that is clean, simple, and not cliché; it does matter, and your readers will appreciate it!

The Designer Who Delivers

POSTED IN Blog | Comments Off

Smashing-magazine-advertisement in The Designer Who Delivers
 in The Designer Who Delivers  in The Designer Who Delivers  in The Designer Who Delivers

Whether you design and code websites all by yourself or run a small business with a pool of talent, you will always face the challenge of how much to work on a design and UI before passing the mock-ups on to the developer? Moreover, how much visual work needs to be done in order to effectively present a website to a client? In this article, we’ll talk about best practices for clear communication, which tools to use and how to manage resources on both small and large projects.

Slide1 in The Designer Who Delivers

[Offtopic: by the way, did you know that Smashing Magazine has one of the most influential and popular Twitter accounts? Join our discussions and get updates about useful tools and resources — follow us on Twitter!]

Determining Factors In Number Of Mock-Ups To Deliver

As the owner of a small business, I have watched our company grow from a part-time, basement-dwelling, under-the-radar operation to a small business with an office, chairs, desks, and staplers (aren’t staplers an indication of legitimacy?). During this process of breaking out of our egg shell, we have birthed a company culture and a set of best practices, and we have gained valuable experience in the field of Web design and development. One of these nuggets of experience is acquiring the ability to save time and money by creating just the right amount of visual material to communicate clearly with both the client and website developer.

I won’t even bother asking whether you’ve ever been assigned to create a custom Web application with an intricate UI, only to see your client pretty well freak out and tell you that it’s completely the opposite of what they had in mind. And let’s be honest: they freaked out not because they’re Web infants who drool every time a Flash intro pops up, but because you failed to communicate the project and its functionality.

Slide2 in The Designer Who Delivers

Don’t get me wrong. Your UI was probably slick. It ran fast, the scripts were minified, it had sprites for all button and UI elements. From a technical and design standpoint, it was as hot as the BMW Mini Cooper back in 2007. The only problem was that your client was looking for a pickup truck.

Our approach to Web design and number of mock-ups is usually based on the size of the project. For the purpose of this article, I’ll break projects into two categories: the brochure website (i.e. a content-oriented website about a company or individual) and the application website.

Brochure Website

For small websites, I recommend you sit down with the client and spend a good hour just learning about their business. Before this meeting, all you probably had to start with was an email from your cousin saying something like, “Listen, Mike over at Gadget Inc. wants a cool site that will be #1 on Google.” After your meeting, though, you will be amazed at the quantity of relevant information that your client shares with you. Don’t be afraid to ask questions: information that would normally be difficult to extract is but a question away when you’re sitting face to face. Your inquisitive attitude will also reassure the client because it indicates that you’re genuinely interested in solving his business problems.

Slide3 in The Designer Who Delivers

Now that you have a wealth of information, you should be able to deduce what the client really wants (it might not be exactly what you originally thought). Make sure you understand well what websites they like and the reasons they like them, along with the colors, logo and other visual cues that might help you get started on the design. If your client has not yet committed to you and is waiting on a proposal, you may want to provide a single mock-up with your proposal. A mock-up is often a worthwhile investment on a larger project, because it creates an emotional attachment with the client and speeds up the bidding process.

This more or less sums it up for small websites: clear communication with the client helps you establish a good base to work from, and the number of mock-ups should be kept to a minimum if you’re good at listening. In case you get stuck on a minute detail that the client doesn’t like, you could always post your mock-up on ConceptFeedback.com or Smashing Magazine Forums and get some feedback from other designers. Most of the time, peer opinion will sway the client to your side if you know what you’re doing.

Application Website

Larger projects and Web applications are a completely different beast and should be dealt with accordingly. Your requirements for the project will arrive as a request for proposal (RFP), sealed in a gold-encrusted money-scented envelope and put together by a project lead. A committee of people will be responsible for the content, functionality and goals of the website, and their opinions will be slightly different. The job of the designer and/or team lead will be to interpret the client’s requirements and communicate them visually to the development team.

I have learned that written technical specifications are only as good as the people who read them. Your developers will understand them, but your client committee will interpret them in as many ways as there are people on the committee. Your responsibility, then, is to illustrate the project for both teams. All of the items mentioned above for the small website still apply, but you will also need to build an information architecture map, functional flow, interaction mock-ups and more. As you’re working through these visual elements, consider using some of the tools available on the Web to get feedback from a wider audience.

Slide4 in The Designer Who Delivers

While mock-ups that encompass detailed functionality are a costly venture, they are simply the best thing you can do before writing a line of code, because an illustration will give your client the right expectations. As a Web development company, you would also be fortunate to have Web designers who understand mark-up, AJAX limitations, accessibility and readability implications and more. We have had some curious interactions with designers who made fantastic brochures but couldn’t mock up a single screen of a website UI.

This approach, while time-consuming at first, will save hundreds of development hours, because the application will behave and look the way the client expects. Your information hierarchy and functionality mock-ups will allow your developer to work completely independently from the designer, with minimal interruption and questions.

Recommended Tools

Red Flags

Even if you follow these guidelines and wield a creative stylus, you will have conversations or get emails that should set off alarms in your head. These communications usually start with, “This is not as hip as I wanted,” or “I was expecting something unexpected,” or “We really want it to look social.” These statements are problematic for a couple of reasons, the first being that you have a limited budget and time frame for the project and have already used up some of them. The second problem is that these statements are as ambiguous as Ricky Martin’s sexuality (not anymore, eh?).

Slide5 in The Designer Who Delivers

Well, just as with the requirement-gathering phase, your focus here should be to drill to the heart of these statements and figure out what exactly is meant by each. The work you have already done can usually be salvaged, and the client might want nothing more than a different illustration, color combination or font stack. I suggest approaching this with changes that require little effort. Start with small tweaks, and then send the mock-ups. Continue with moderately complex changes, and then send the mock-ups. Rinse and repeat. What you will find through these small adjustments and your communications is that the negativity in their initial email was actually an exaggeration of a small issue.

Lessons Learned

The route you take in a successful project will depend on the size and composition of your team and your ability to communicate with the client. The more projects our team completes, the more strongly we believe in visual communication, which falls strictly on the designer’s shoulders. It is also safe to say that a Web designer is a mixed and intricate breed of professional: an individual who must understand business, be able to read customers, stay creative and fresh with visual solutions, and be technical enough to understand Web technology limitations and best practices.

Additional Articles

(al)


© Aurimas Adomavicius 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:

Smashing-magazine-advertisement in PHP: What You Need To Know To Play With The Web
 in PHP: What You Need To Know To Play With The Web  in PHP: What You Need To Know To Play With The Web  in PHP: What You Need To Know To Play With The Web

In this article, I’ll introduce you to the fundamentals of PHP. We’ll focus on using PHP to access Web services and on turning static HTML pages into dynamic ones by retrieving data from the Web and by showing different content depending on what the user has entered in a form or requested in the URL.

You won’t come out a professional PHP developer, but you’ll be well on your way to building a small page that uses Web services. You can find a lot of great PHP info on the Web, and most of the time you will end up on PHP.net itself. But I was asked repeatedly on several hack days and competitions to write this quick introduction article, so here it is.

[Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #1 is Professional Web Design, 242 pages for just $9,90.]

What Is PHP?

PHP is a server-side language that has become a massive success for three reasons:

  • It is a very easy and forgiving language. Variables can be anything, and you can create them anytime you want.
  • It is part of the free LAMP stack (Linux, Apache, MySQL, PHP) and thus available on almost any server you can rent on the Web.
  • It does not need a special editor, environment or build process. All you do is create a file of the .php file type, mix PHP and HTML and then put it on your server for rendering.

Installing PHP Locally, And Your First Code

To run PHP locally on your computer, you’ll need a local server with PHP enabled. The easiest way to do this is to download and install MAMP for OS X or XAMPP for Windows. Once you’ve installed any of these packages, you can start using PHP. Simply create a file named index.php in the htdocs folder of your MAMP or XAMPP installation.

In this file, type (or copy and paste) the following:

<?php
  $myname = 'Chris';
  echo '<p>This is PHP</p>';
  echo "<p>My name is $myname</p>"
  echo '<p>My name in another notation is still  '.$myname.'</p>';
?>

If you open this file in a browser by accessing your XAMPP or MAMP installation (via http://localhost/index.php or http://localhost:8888/index.php), you should see the following:

This is PHP
My name is Chris
My name in another notation is still Chris

But you won’t see that. The problem is that the third line does not end in a semicolon (;). This is an error. Depending on your PHP installation, you’ll get either an error message or simply nothing. If you get nothing, then find the file named php_error.log on your hard drive, and open it. It will tell you what went wrong.

Phperrorlog1 in PHP: What You Need To Know To Play With The Web

The first thing to remember, then, is that every line of PHP has to end in a semicolon. If we fix this problem, we get this result:

Php-rendered1 in PHP: What You Need To Know To Play With The Web

<?php
  $myname = 'Chris';
  echo '<p>This is PHP</p>';
  echo "<p>My name is $myname</p>";
  echo '<p>My name in another notation is still  '.$myname.'</p>';
?>

We can see here the first few important features of PHP:

  • PHP blocks start with <?php and end with ?>. Anything between these two commands is interpreted as being PHP and returned to the document as HTML.
  • Every line of PHP has to end with a semicolon (;), or else it is an error.
  • Variables in PHP start with a $, not with the var keyword as you do in JavaScript (this is where it gets confusing with jQuery and Prototype).
  • You print content to the document in PHP with the echo command. There is also a print command, which does almost the same, so you can use that, too.
  • In this example, we have defined a string named myname as “Chris”. To print it with the echo command surrounded by other text, you need to either embed the variable name in a text with quotation marks or concatenate the string with a full stop when you use single quotation marks. This is line 3 and 4: they do the same thing but demonstrate the different syntax. Concatenation is always achieved with a full stop, never with a + as you do in JavaScript.

You can jump in and out of PHP anywhere in the document. Thus, interspersing PHP with HTML blocks is totally fine. For example:

<?php
  $origin = 'Outer Space';
  $planet = 'Earth';
  $plan = 9;
  $sceneryType = "awful";
?>
<h1>Synopsis</h1>

<p>It was a peaceful time on planet <?php echo $planet;?>
and people in the <?php echo $sceneryType;?> scenery were unaware
of the diabolical plan <?php echo $plan;?> from <?php echo $origin;?>
that was about to take their senses to the edge of what could be endured.</p>

This outputs the following:

Variables-rendered1 in PHP: What You Need To Know To Play With The Web

Are you with me so far? To show something on the screen, particularly numbers or a string, we use echo. To show more complex structures, we need loops or specialized debugging methods.

Displaying More Complex Data Types

You can define arrays in PHP using the array() method:

$lampstack = array('Linux','Apache','MySQL','PHP');

If you simply want to display a complex data type like this in PHP for debugging, you can use the print_r() command:

$lampstack = array('Linux','Apache','MySQL','PHP');
print_r($lampstack);

This gives you all the information, but it doesn’t help you structure it as HTML:

Print R-demo1 in PHP: What You Need To Know To Play With The Web

For this, you need to access the elements with the array counter. In PHP this is done with the [] brackets:

<ul>
<?php
$lampstack = array('Linux','Apache','MySQL','PHP');
echo '<li>Operating System:'.$lampstack[0] . '</li>';
echo '<li>Server:' . $lampstack[1] . '</li>';
echo '<li>Database:' . $lampstack[2] . '</li>';
echo '<li>Language:' . $lampstack[3] . '</li>';
?>
</ul>

See this demo in action.

This is, of course, stupid programming because it is not flexible. If a computer is able to the dirty work for you, make it do it. In this case, we can define two arrays and use a loop:

<ul>
<?php
$lampstack = array('Linux','Apache','MySQL','PHP');
$labels = array('Operating System','Server','Database','Language');
$length = sizeof($lampstack);
for( $i = 0;$i < $length;$i++ ){
  echo '<li>' . $labels[$i] . ':' . $lampstack[$i] . '</li>';
}
?>
</ul>

The for loop works the same as it does in JavaScript. The only difference is that you read the size of an array not with array.length but with sizeof($array).

Again, this example is not very clever because it assumes that both the $lampstack and the $labels array are of the same length and in the same order. Instead of using this, I’d use an associated array:

<ul>
<?php
$lampstack = array(
  'Operating System' => 'Linux',
  'Server' => 'Apache',
  'Database' => 'MySQL',
  'Language' => 'PHP'
);
$length = sizeof($lampstack);
$keys = array_keys($lampstack);
for( $i = 0;$i < $length;$i++ ){
  echo '<li>' . $keys[$i] . ':' . $lampstack[$keys[$i]] . '</li>';
}
?>
</ul>

The function array_keys() gives you back all the keys of an array as an array itself. This way, we can display the keys and the values at the same time.

A shorter way to achieve the same principle, and which works with both arrays and objects, is to use the foreach() loop construct:

<ul>
<?php
$lampstack = array(
  'Operating System' => 'Linux',
  'Server' => 'Apache',
  'Database' => 'MySQL',
  'Language' => 'PHP'
);
foreach( $lampstack as $key => $stackelm ){
  echo '<li>' . $key . ':' . $stackelm . '</li>';
}
?>
</ul>

This is the shortest way to display a complex construct. But it will fail when $lampstack is not an array. So, checking for sizeof() is still a good plan. You can do this with a conditional.

Using Conditionals

Conditionals are “if” statements, both in the English language and in almost any programming language I know. So, to test whether an array is safe to loop over, we could use the sizeof() test:

<ul>
<?php
$lampstack = array(
  'Operating System' => 'Linux',
  'Server' => 'Apache',
  'Database' => 'MySQL',
  'Language' => 'PHP'
);
if( sizeof($lampstack) > 0 ){
  foreach( $lampstack as $key => $stackelm ){
    echo '<li>' . $key . ':' . $stackelm . '</li>';
  }
}
?>
</ul>

Common conditionals are:

  • if($x > 10 and $x < 20)
    Is $x bigger than 10 and less than 20?
  • if(isset($name))
    Has the variable $name been defined?
  • if($name == 'Chris')
    Does the variable $name have the value of "Chris"?
  • if($name == 'Chris' or $name == 'Vitaly')
    Does the variable $name have the value of "Chris" or "Vitaly"?

Cool, but what if we want to make this reusable?

Functions In PHP

To make a task even more generic, we can write a function. In this case, we put the loop and the testing in a function and simply call it with different arrays:

<?php
function renderList($array){
  if( sizeof($array) > 0 ){
    echo '<ul>';
    foreach( $array as $key => $item ){
      echo '<li>' . $key . ':' . $item . '</li>';
    }
    echo '</ul>';
  }
}
$lampstack = array(
  'Operating System' => 'Linux',
  'Server' => 'Apache',
  'Database' => 'MySQL',
  'Language' => 'PHP'
);
renderList($lampstack);

$awfulacting = array(
  'Natalie Portman' => 'Star Wars',
  'Arnold Schwarzenegger' => 'Batman and Robin',
  'Keanu Reaves' => '*'
);
renderList($awfulacting);
?>

Note that functions do not begin with a dollar sign.

We've already seen most of the magic of PHP. The rest is all about building functions to do all kinds of things: converting strings, sorting arrays, finding things in other things, accessing the file system, setting cookies and much more, each of which does one and only one thing right. I keep catching myself writing complex functions in PHP, only to realize from looking at the documentation that a native function already exists for it.

Interacting With The Web: URL Parameters

Let's start playing with the Web in PHP… or, more precisely, playing with information that comes from the browser's address bar or with forms that we can re-use. To get parameters from the current URL, we use the global $_GET array. So, if you call the index.php script with http://localhost/index.php?language=fr&font=large, you can change the display and locale by checking for these settings. The language parameter will be available as $_GET['language'], and the font parameter as $_GET['font']:

<?php
$name = 'Chris';

// if there is no language defined, switch to English
if( !isset($_GET['language']) ){
  $welcome = 'Oh, hello there, ';
}
if( $_GET['language'] == 'fr' ){
  $welcome = 'Salut, ';
}
switch($_GET['font']){
  case 'small':
    $size = 80;
  break;
  case 'medium':
    $size = 100;
  break;
  case 'large':
    $size = 120;
  break;
  default:
    $size = 100;
  break;
}
echo '<style>body{font-size:' . $size . '%;}</style>';
echo '<h1>'.$welcome.$name.'</h1>';
?>

This means we can now send URL parameters to change the behavior of this document:

Parameters1 in PHP: What You Need To Know To Play With The Web

Notice that predefining a set of values that are acceptable for a certain parameter is always best. In the earlier example, we may as well have set the font size in pixels as a parameter and then written that to the document—but then we would have needed a good validation script to prevent end users from sending bad values or even malicious code through the parameter.

Sending malicious code via a parameter without filtering is called cross-site scripting (XSS), and it is one of the big security problems of the Web. You can prevent it by not printing out the values of parameters, and instead using them in comparisons, and by using the filters provided by PHP.

Say you want to allow users to enter data in a form that you will display later on. Make sure to filter out the results:

<?php
  $search_html = filter_input(INPUT_GET, 's',
                              FILTER_SANITIZE_SPECIAL_CHARS);
  $search_url = filter_input(INPUT_GET, 's',
                             FILTER_SANITIZE_ENCODED);
?>
<form action="index.php" method="get">
  <div>
    <label for="search">Search:</label>
    <input type="text" name="s" id="search"
           value="<?php echo $search_html;?>">
  </div>
  <div class="bar"><input type="submit" value="Make it so"></div>
</form>
<?php
if(isset($_GET['s'])){
  echo '<h2>You searched for '.$search_html.'</h2>';
  echo '<p><a href="index.php?search='.$search_url.'">Search again.</a></p>';
}
?>

See this filtering example in action. Without the filters, attackers could send parameters like index.php?s="<script>, which would execute third-party code on your website. With filtering, this malicious code is converted to HTML entities.

If you want to use POST as the method to send the data in your form, then the PHP variables will change accordingly to $_POST for the array and INPUT_POST for the filter.

Loading Content From The Web

PHP comes with a lot of file functions that allow you to read and write files from the hard drive or to load content from the Web. I've found, however, that for security reasons a lot of hosting companies disable them, especially when you try to read content from a third-party resource. The workaround is to use cURL to load information from the Web. cURL is a tool that allows you to make HTTP requests to retrieve information—a kind of browser in command-line form. I've written a detailed post about cURL and how to use it. Here, then, is a simple use case to illustrate:

<?php
  // define the URL to load
  $url = 'http://www.smashingmagazine.com';
  // start cURL
  $ch = curl_init();
  // tell cURL what the URL is
  curl_setopt($ch, CURLOPT_URL, $url);
  // tell cURL that you want the data back from that URL
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  // run cURL
  $output = curl_exec($ch);
  // end the cURL call (this also cleans up memory so it is
  // important)
  curl_close($ch);
  // display the output
  echo $output;
?>

If you run this in the browser, you'll see Smashing Magazine's home page.

Smashingmagwithcurl1 in PHP: What You Need To Know To Play With The Web

You could also strip out content from the data:

<?php
  // define the URL to load
  $url = 'http://www.smashingmagazine.com';
  // start cURL
  $ch = curl_init();
  // tell cURL what the URL is
  curl_setopt($ch, CURLOPT_URL, $url);
  // tell cURL that you want the data back from that URL
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  // run cURL
  $output = curl_exec($ch);
  // end the cURL call (this also cleans up memory so it is
  // important)
  curl_close($ch);
  // if a filter parameter with the value links was sent
  if($_GET['filter'] == 'links'){
    // get all the links from the document and show them
    echo '<ul>';
    preg_match_all('/<a[^>]+>[^<\/a>]+<\/a>/msi',$output,$links);
    foreach($links[0] as $l){
      echo '<li>' . $l . '</li>';
    }
    echo'</ul>';
  // otherwise just show the page
  } else {
    echo $output;
  }
?>

If you open this in your browser, you'll get all of the links from Smashing Magazine and no other content.

Links1 in PHP: What You Need To Know To Play With The Web

Nowadays, though, we are more likely to use APIs than to load websites this way, which is why we need a way to convert the XML and JSON that are returned from Web services into PHP-friendly data.

Displaying XML Content

The easiest way to deal with XML content in PHP is to use the SimpleXML functions of PHP. Using these, we can turn a bunch of XML into a PHP object and loop over it. To show Smashing Magazine's RSS feed, we can do the following:

<?php
  $url = 'http://rss1.smashingmagazine.com/feed/';
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $output = curl_exec($ch);
  curl_close($ch);
  $data = simplexml_load_string($output);
  echo '<ul>';
  foreach($data->entry as $e){
    echo '<li><a href="' . $e->link[0]['href'] .
         '">'.$e->title.'</a></li>';
  }
  echo '</ul>';
?>

The simplexml_load_string() function turns the XML document into a PHP object with arrays. How did I figure out to loop over data->entry and get the href via link[0]['href']? Simple. I did a print_r($output) and checked the source of the document by hitting Cmd + U in Firefox on my Mac. That showed me that this entry is an array. I then did a print_r($e) in the loop to see all the properties of every entry. If it is part of the @attributes array, then you need to use the [] notation.

That's all. The only stumbling block you will encounter is CDATA blocks and namespaces in SimpleXML. Stuart Herbert has a good introduction to these two issues in this article.

Displaying JSON Content

The data format JSON is the low-fat alternative to XML. It is far less complex (e.g. no namespaces), and if you work in a JavaScript environment, it is native to the browser. This makes it very fast and easy to use, and for this reason it has started to become a popular data format for APIs. In essence, JSON is a JavaScript object. For example, I could write the LAMP stack example as follows:

{"lampstack":
  {
    "operatingsystem" : "Linux",
    "server" : "Apache",
    "database" : "MySQL",
    "language" : "PHP"
  }
}

You can convert this to PHP using the json_decode() method, and get it back as a PHP object:

<?php
  $json = '{
  "lampstack":
  {
    "operatingsystem":"Linux",
    "server":"Apache",
    "database":"MySQL",
    "language":"PHP"
    }
  }';
  print_r(json_decode($json));
?>

One API that returns JSON is the Twitter trends API. If you load the API's URL with cURL and do a print_r() after json_decode(), you get the following back:

<?php
  $url = 'http://search.twitter.com/trends.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);
  print_r($data);
?>
stdClass Object
(
[trends] => Array
  (
    [0] => stdClass Object
    (
      [name] => #nowplaying
      [url] => http://search.twitter.com/search?q=%23nowplaying
    )

    [1] => stdClass Object
    (
      [name] => #Didntwannatellyou
      [url] => http://search.twitter.com/search?q=%23Didntwannatellyou
    )

    [2] => stdClass Object
    (
      [name] => #HappyBirthdayGagaBR
      [url] => http://search.twitter.com/search?q=%23HappyBirthdayGagaBR
    )

    [3] => stdClass Object
    (
      [name] => Justin Bieber
      [url] => http://search.twitter.com/search?q=%22Justin+Bieber%22
    )

    [4] => stdClass Object
    (
      [name] => #FreakyFactSays
      [url] => http://search.twitter.com/search?q=%23FreakyFactSays
    )

    [5] => stdClass Object
    (
      [name] => #YouSoGangsta
      [url] => http://search.twitter.com/search?q=%23YouSoGangsta
    )

    [6] => stdClass Object
    (
      [name] => I ?
      [url] => http://search.twitter.com/search?q=%22I+%E2%99%A5%22
    )

    [7] => stdClass Object
    (
      [name] => #MeMyselfandTime
      [url] => http://search.twitter.com/search?q=%23MeMyselfandTime
    )

    [8] => stdClass Object
    (
      [name] => #2010yearofJonas
      [url] => http://search.twitter.com/search?q=%232010yearofJonas
    )

    [9] => stdClass Object
    (
      [name] => Easter
      [url] => http://search.twitter.com/search?q=Easter
    )
  )
  [as_of] => Sun, 28 Mar 2010 19:31:30 +0000
)

You can then use a simple loop to render the current trends as an unordered list:

<?php
  $url = 'http://search.twitter.com/trends.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);
  echo '<h2>Twitter trending topics ('.$data->as_of.')</h2>';
  echo '<ul>';
  foreach ($data->trends as $t){
    echo '<li><a href="'.$t->url.'">'.$t->name.'</a></li>';
  }
  echo '</ul>';
?>

Putting It All Together

Let's do a quick example using all of the things we've learned so far: a simple search interface for the Web.

Using Yahoo's YQL, it is pretty easy to do a Web search for "cat" with the command select * from search.web where query="cat" sent to the YQL endpoint. You can define JSON as the return format, and the rest means you simply enhance the earlier form example:

<?php
  $search_html = filter_input(INPUT_GET, 's', FILTER_SANITIZE_SPECIAL_CHARS);
  $search_url = filter_input(INPUT_GET, 's', FILTER_SANITIZE_ENCODED);
?>
<form action="index.php" method="get">
  <div>
    <label for="search">Search:</label>
    <input type="text" name="s" id="search"
           value="<?php echo $search_html;?>">
   <input type="hidden" name="demo" value="17">
   <input type="submit" value="Make it so">
  </div>
</form>
<?php
if(isset($_GET['s'])){
  echo '<h2>You searched for '.$search_html.'</h2>';
  $yql = 'select * from search.web where query="'.$search_url.'"';
  $url = 'http://query.yahooapis.com/v1/public/yql?q='.
          urlencode($yql).'&format=json&diagnostics=false';
  $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);
  echo '<ul>';
  foreach ($data->query->results->result as $r){
    echo '<li><h3><a href="'.$r->clickurl.'">'.$r->title.'</a></h3>'.
         '<p>'.$r->abstract.' <span>('.$r->dispurl.')</span></p></li>';
  }
  echo '</ul>';

  echo '<p><a href="index.php?search='.$search_url.'&demo=17">Search again.</a></p>';
}
?>

Interaction With JavaScript

One thing people keep asking about is how to send information from PHP to JavaScript and back. This can be done in a few ways.

  • To send information from JavaScript to PHP, you need to either alter the href of a link or populate a hidden form field. The other solution of course is to use AJAX.
  • To send information from PHP to JavaScript, simply render a script element and write out the PHP information with an echo statement.
  • Using PHP's header() function and json_encode(), you can send data back to the browser as JavaScript, which allows us to use it as a src attribute of a script node.

For example, to get Smashing Magazine's RSS feed as a JavaScript object, you could do the following:

<?php
  header('Content-type: text/javascript');
  $url = 'http://rss1.smashingmagazine.com/feed/';
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $output = curl_exec($ch);
  curl_close($ch);
  $data = simplexml_load_string($output);
  $data = json_encode($data);
  echo 'var smashingrss='.$data;
?>

You could then use this in a JavaScript block:

<script src="http://icant.co.uk/articles/phpforhacks/index.php?demo=18"></script>
<script>alert(smashingrss.title);</script>

Using header() and json_encode(), you could do any complex conversion and filtering in PHP and re-use it in JavaScript.

Summary

I hope this gives you an idea of what PHP is and how you can use it to access Web services and to build your own APIs to re-use in JavaScript. Using PHP for the Web boils down to a few tricks:

  • Use cURL to load data from Web resources;
  • Convert information with simplexml_load_string() and json_decode();
  • Check the structure of returned information with print_r();
  • Loop over information with foreach();
  • Use the $_GET[] and $_POST[] arrays to re-use form data and URL parameters;
  • Filter information from the user and from URLs using the built-in PHP filtering methods.

A lot of documentation is out there, and your best bet is to go directly to the PHP home page to read or download the documentation. Check out the user comments in particular, because that is where the real gems and examples of implementation appear.

(al)


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

Smashing-magazine-advertisement in The Gradual Disappearance Of Flash Websites
 in The Gradual Disappearance Of Flash Websites  in The Gradual Disappearance Of Flash Websites  in The Gradual Disappearance Of Flash Websites

If you want to “go big” visually with a website, delivering complex interaction and a rich experience across a wide range of browsers, Flash is the only way to go. Right? Nope. Given the widespread adoption and advancements of modern browsers and JavaScript libraries, using Flash makes little sense. But it does have its place on the Web, considering the need for progressive enhancement.

In the current landscape of technology and accessing the Internet through devices such as picture frames, netbooks, cell phones and televisions, the benefits of Web standards outweigh those of Flash, especially when delivering content to a broad audience on various devices.

Flash is a proprietary product that sits on top of the browser to extend functionality. While Flash may have provided missing functionality for some time, it brings little value to modern browsers. As more and more designers and developers realize the benefits of Web standards and start using some of the features of HTML5 and CSS3, we’ll see fewer Flash-driven websites.

[Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #1 is Professional Web Design, 242 pages for just $9,90.]

The Great Flash vs. Web Standards Debate

Advocates have evangelized Web standards for over 10 years. The debate among developers and designers often gets as heated as the discussion on same-sex marriage, causing uncomfortable divisions among some of the smartest people in the field.

A1 in The Gradual Disappearance Of Flash Websites

With the recent announcement of iPad’s lack of Flash support and the continued lack of it on the iPhone, the debate has reached beyond the development community to include Adobe and Apple themselves. With Apple’s anti-Flash stance, it has become too hard to argue for a completely Flash-based website when it would leave out a potentially large audience.

Eventually, Flash will make it to mobile devices (250 million devices are expected to have full support by the end of 2012), but that’s really only a small part of the debate and one of the better arguments that Web standards advocates have.

At the heart of the matter is how to deliver a great experience to users no matter the technology or platform.

“HTML5 vs. Flash” is the wrong discussion. “Accessible rich media” is the right one.

— Jeffrey Zeldman (via Twitter)

In the end, we’re all just trying to create websites that can be accessed and used, regardless of the tools we use to deliver them.

Healthy Competition

In the early days of the Web, Flash was pretty much the only way to deliver a rich experience across different browsers and platforms. CSS and JavaScript were inconsistently supported across browsers, and relying on them was hardly worth the trouble.

A2 in The Gradual Disappearance Of Flash Websites
(Image: Erik Charlton)

Flash saw great success early on and pushed forward quickly. The small app that once mainly made animations quickly became a worthy development environment in its own right. Developers and designers alike chose to concentrate their efforts in that area, often segregating themselves from the open Web and backing the proprietary technology. Flash websites took over the Web, and Web standards didn’t allow developers to create the experiences that users were starting to expect.

Web standards may have fallen behind once, but they continued to be pushed forward by practitioners and those willing to embrace the idea of an open Web.

Web Standards: Benefits And Reasons For Adoption

Users expect rich experiences, and in many cases these great experiences are now being delivered with HTML, CSS and JavaScript, which are the basics of Web standards.

A3 in The Gradual Disappearance Of Flash Websites
(Image: The US Army)

The line between websites developed with Flash and Web standards has become blurred. At first glance, even the savviest developer would have a hard time discerning which technology was used for a website without peeking at the source.

The list of websites that are ditching Flash in favor of Web standards is growing every day. Even if these decisions are driven by the iPad and iPhone’s lack of Flash, they’ll soon reap the other benefits that Web standards bring.

Current Trends

What once could be done almost exclusively in Flash is now easily accomplished with JavaScript and a bit of ingenuity. Lightboxing, scrolling news stories, rich navigation and image slideshows were once solely the domain of Flash. Widespread adoption of standards is easily attributable to the ease of using JavaScript libraries for enhanced interaction and current support of CSS among browsers.

Video has been an important step in moving Web standards forward. Video is one of the few things that could once only be delivered in Flash. The biggest leap so far has been YouTube’s adoption of the HTML5 video element (albeit in beta), allowing modern browsers to bypass the Flash plug-in and use video native to the browser’s player.

HTML5 video has encountered controversy (thanks to the current codec debacle) and reports of unimpressive performance, but these issues will be worked out. Website developers will implement HTML5 video and choose an appropriate codec. When the biggest websites make this decision, we’ll end up with a de facto standard that gives browsers improved performance.

Modern Browser Adoption

HTML5 and CSS3 represent a great effort to advance native browser performance, and many browser providers are already implementing their specifications, even through they haven’t been set in stone. We have a lot to look forward to with CSS animation, canvas, local storage, geo-location and other specifications that will bring Web standards into a new era.

Although it will be many years before we see 100% of the emerging specifications implemented in browsers and see a large majority of users upgrade to those browsers, if we embrace the progressive enhancement of content, we’re well on our way to pushing adoption among developers.

Progressive Enhancement

Learning to produce progressively enhanced content, giving up pixel-perfect rendering in every browser, and embracing graceful degradation in older browsers can free up time to concentrate on other areas of development, such as accessibility and platform-delivery agnosticism.

A15 in The Gradual Disappearance Of Flash Websites
(Image: Unobtrusify.com)

If users of your website don’t have JavaScript or CSS enabled, they can still access and enjoy your content in a more limited way, unlike Flash websites, which typically don’t deliver content in the absence of Flash or JavaScript.

Designing with progressive enhancement in mind and building from the ground up require designers and developers to think more about the infrastructure of a website, and this typically exposes the kinds of issues that arise when working from the top down (i.e. designing a website and then considering the fall-back).

Smart Phone Browsers and Context Delivery

The mobile Web is still in its infancy and usually an afterthought in the design process, but standard-based designs can degrade as nicely on phones as they do on older desktop browsers. In the absence of the Flash plug-in, a website can still deliver an exceptional experience without much extra effort (which would be cumbersome with a Flash website).

Mobile Web browsing is increasing exponentially, and ignoring these users is unwise. Web standards are the only option to deliver richer interactions in mobile browsers.

Content Management

Giving website owners and editors the ability to edit interactive content inside a content management system means not having to coordinate with Flash developers to create and maintain content outside of the system. Many agencies have ditched Flash for WordPress-powered websites that use JavaScript to enhance the experience, allowing for quick and easy updates to portfolios and content.

Openness

Web standards being what they are (i.e. standard agreement on the way code is constructed and served), user agents and scripts from outside a website can be written to access data directly from the HTML. Search engines, microformats, feeds, translation and bookmarklets all work because of the open nature and consistency between the data.

A8 in The Gradual Disappearance Of Flash Websites
(Image: Monica’s Dad)

If we want the Web to be truly scalable and interconnected, then microformats and microdata and APIs for content might be just the answer. Otherwise, we’ll remain in the same position we were years ago when websites erected walls around their content.

Freedom

Many people believe that the technology behind the Internet should be open and not competitive as it has been in the past. People should be free to consume and create information, without being tied down to the kind licensing restrictions and legalities seen with the likes of Flash, Silverlight and other corporately owned technologies.

Creating and delivering content with Web standards not only is the best technological solution but supports the freedom of an open Web.

Flash Does, And Will Continue To Do, Many Things Well

Just because Flash-driven websites are gradually disappearing doesn’t mean that Flash will disappear altogether. Too much content and infrastructure have been set up to magically vanish. Without vast restructuring or realigning of organizations and processes, plenty of Flash developers will continue to be employed, and plenty of Flash advertising will be directed at those ready to ignore it.

We owe a lot to Flash for making the Web what it is today, and it deserves that credit. Even though it showed less potential compared to the other plug-in technologies, such as Java applets, that emerged early on, it had a nice balance between seamless delivery to users and ease of development and deployment. Many other Web technologies, such as VRML and SVG, have tried to overcome Flash’s hold on the Web but have continually fallen short.

Where would the Internet be without Flash and the innovations it brought?

Ease of Use

Out of the gate, Flash was intuitive and easy-to-use application for both designers and developers, delivering the simplest of animations, yet able to scale to serve complex applications.

A13 in The Gradual Disappearance Of Flash Websites
(Image: *ejk*)

Because of its ease of use, Flash posed a lower barrier to entry for budding designers and developers. And combined with the suite of applications from Adobe, Flash fits well in the designer’s workflow.

Consistency

You can’t argue with the fact that for many years Flash has been the only way to deliver rich interaction in a consistent way across a wide range of platforms and browsers. It’s still the only way to deliver video and audio to older browsers, and it will retain its throne for several more years.

If you’re a stickler for fonts and demand special ones for your website, then you’ll be saddened by the current state of font support in the browser. This shortcoming will have to be compensated by Flash and swfObject until @font-face and various font formats become more widely supported.

Standards Not Quite There

As much as Web standards have advanced, we’re often stuck having to support older browsers in which Flash may be the only way to deliver audio, video and complex data-heavy interfaces. Thanks to early adopting Web browser providers, we can start using the HTML5 audio and video tag today. But we still have to plan for a Flash fall-back to deliver media in older browsers.

The same could be said for the canvas element for delivering complex visualization, 3-D animation and games. If a browser like IE6 needs to be supported, providing a decent fall-back for the canvas element can be complicated. Flash might just be the best choice for development in such cases. As always, your current and potential audience should determine your direction.

Progressively Enhanced Flash and Flash Injection

The best Flash developers take the same approach as the Web standards crowd, using Flash as a layer to enhance their websites and applications. If that continues, Flash will continue to have a place in delivering a great experience, serving mobile devices and reaching search engines and other user agent technologies. The Flash injection technique is the easiest way to meld the best of both worlds.

The Future of Flash

Adobe has never been the type of company to let a product stagnate. You can be sure it will keep pushing to get Flash on as many mobile devices as possible.

A14 in The Gradual Disappearance Of Flash Websites
(Image: Robert Weißenberg)

With Creative Suite 5, developers will be able to output Flash projects as native iPhone applications using the iPhone Packager. And Flash could soon evolve from its early roots as an animation application to a full-fledged desktop and mobile application development environment with the help of AIR and related advancements (AIR might reach the mobile space pretty quickly).

Flash developers will likely be in even greater demand, as the demand to deliver applications consistently between desktop and mobile devices increase—even if they aren’t asked to create run-of-the-mill websites.

Flash, HTML, CSS And JavaScript Are Just Tools

Web standards and Flash (and other plug-in technologies) are simply tools to create content for the Web. Even if Flash is on the decline for websites, Flash developers have no reason to worry about becoming obsolete.

Everything that is true for creating rich Internet applications holds true for whatever other tool you use, and transitioning to Web standards development may be easier than you think.

A16 in The Gradual Disappearance Of Flash Websites
(Image: kansas_city_royalty)

Flash and Web standards developers have more in common than they don’t. Interface and interaction design, typography, layout, graphic design and object-oriented programming are all still valid and important for both technologies.

Developers on both sides of the spectrum struggle with many of the same issues. They both set out to create a great user experience, to design intuitive interactions and to make websites easy for users. All of this is done not by the technology itself but by the people behind it.

Standards-Based Websites That Shine

Here are some examples of websites that have embraced Web standards and offer rich interaction. If you want to keep up with current trends, many great standards-based websites are featured on showcase websites such as NotCoffee and jQuery Style.

Pigeon and Pigeonette
This website has a single page that transitions during navigation. Other than being informational, it offers a couple of Flash games.

S1 in The Gradual Disappearance Of Flash Websites

Good Works Media
An agency website with an accordion home page and lightbox for the portfolio.

S3 in The Gradual Disappearance Of Flash Websites

Made by Elephant
A minimalist portfolio website with a horizontal accordion.

S5 in The Gradual Disappearance Of Flash Websites

Euna (English translation)
A single-page website with very “elastic” transitions.

S6 in The Gradual Disappearance Of Flash Websites

Artopod (English translation)
A retro design with a fixed-height “window” onto the content.

S7 in The Gradual Disappearance Of Flash Websites

DreamerLines
Bold, colorful, full-screen imagery on a single page, with a lightbox portfolio.

S8 in The Gradual Disappearance Of Flash Websites

Serial Cut
Mainly full-screen imagery for a portfolio that includes 3-D, graphic design and photography.

S9 in The Gradual Disappearance Of Flash Websites

Alfa-Bank: U2 (English translation)
The main layout and background imagery changes during navigation.

S10 in The Gradual Disappearance Of Flash Websites

Kobe
A more traditional website but with subtle navigation effects and transitions for imagery and content.

S11 in The Gradual Disappearance Of Flash Websites

Unowhy (English translation)
Another accordion website, with smooth content transitions and a lot of “hover” effects.

S12 in The Gradual Disappearance Of Flash Websites

Creative People
Very creative imagery, heavy on the AJAX, with many examples of the studio’s work.

S13 in The Gradual Disappearance Of Flash Websites

World of Merix
A full-screen draggable map of the agency’s clients, with a smooth lightbox for the content.

S14 in The Gradual Disappearance Of Flash Websites

The Sixty One
Very much an application, this streaming music service lets you browse artists and related info. As you listen, information pops up on the band.

S15 in The Gradual Disappearance Of Flash Websites

Banadies Architech
A website highlighting the work of an architecture firm. With each click on the navigation, the page elegantly shifts around.

S16 in The Gradual Disappearance Of Flash Websites

Paul J. Noble
A dark portfolio website, with an interesting approach to navigation.

S17 in The Gradual Disappearance Of Flash Websites

Adult Swim Shows
A recent relaunch, with full-screen images for navigation.

S20 in The Gradual Disappearance Of Flash Websites

Glyde
A marketplace website with a simple interface, carousel navigation for products and lightboxes for detailed descriptions.

S21 in The Gradual Disappearance Of Flash Websites

Alex Arts
Personal portfolio of Alex Abramov, with full-screen imagery and pop-up content.

S22 in The Gradual Disappearance Of Flash Websites

Rix
Personal portfolio of Adam Rix. Full-screen imagery and subtle navigation.

S23 in The Gradual Disappearance Of Flash Websites

Eric Johansson
A personal portfolio, with a fun design and scrollable interface.

S24 in The Gradual Disappearance Of Flash Websites

Websites From The (Near) Future

Here are some “experimental” websites that demonstrate what’s becoming possible with Web standards. Be warned: these might work only in the most modern of browsers. To keep up with emerging standards-based websites, check out CanvasDemos and Chrome Experiments.

Bespin
An online code editor from Mozilla.

F1 in The Gradual Disappearance Of Flash Websites

Sketchpad
A simple painting program.

F2 in The Gradual Disappearance Of Flash Websites

JavaScript Wolfenstein 3D, from Nihilogic
The classic game created with Web standards.

F3 in The Gradual Disappearance Of Flash Websites

Leaf Transform, from Disegno Cetell
A simple falling leaf using the canvas element.

F4 in The Gradual Disappearance Of Flash Websites

Canvas Animation Demo
A cartoon animation using the canvas element

F5 in The Gradual Disappearance Of Flash Websites

Canvas Experiment, from 9elements
An audio visualization that reacts to your mouse.

F6 in The Gradual Disappearance Of Flash Websites

Ball Pool
A physics-based demo that lets you drag and push around multi-colored circles.

F7 in The Gradual Disappearance Of Flash Websites

Dynamic Content Injection, from Paul Rouget of Mozilla
An “almost” augmented reality demo that inject images into a video.

F8 in The Gradual Disappearance Of Flash Websites

Canopy Animation
A visualization of a tree that mutates and blooms.

F9 in The Gradual Disappearance Of Flash Websites

Bean
Images falling on the screen.

F10 in The Gradual Disappearance Of Flash Websites

3-D Cube Demo
A draggable, zoomable 3-D cube of colors.

F11 in The Gradual Disappearance Of Flash Websites

JavaScript Bike
A game in which you navigate your motorcycle across a terrain.

F12 in The Gradual Disappearance Of Flash Websites

Comments Visualization
A visualization of comments over time by Matt Ryall using Processing.js.

F13 in The Gradual Disappearance Of Flash Websites

HTML vs. Flash Resources

Here are a few fairly recent articles. Make sure to check out their comments.

(al)


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

Smashing-magazine-advertisement in Holistic Web Browsing: Trends Of The Future
 in Holistic Web Browsing: Trends Of The Future  in Holistic Web Browsing: Trends Of The Future  in Holistic Web Browsing: Trends Of The Future

The future of the Web is everywhere. The future of the Web is not at your desk. It’s not necessarily in your pocket, either. It’s everywhere. With each new technological innovation, we continue to become more and more immersed in the Web, connecting the ever-growing layer of information in the virtual world to the real one around us. But rather than get starry-eyed with utopian wonder about this bright future ahead, we should soberly anticipate the massive amount of planning and design work it will require of designers, developers and others.

Glasses in Holistic Web Browsing: Trends Of The Future

The gap between technological innovation and its integration in our daily lives is shrinking at a rate much faster than we can keep pace with—consider the number of unique Web applications you signed up for in the past year alone. This has resulted in a very fragmented experience of the Web. While running several different browsers, with all sorts of plug-ins, you might also be running multiple standalone applications to manage feeds, social media accounts and music playlists.

Even though we may be adept at switching from one tab or window to another, we should be working towards a more holistic Web experience, one that seamlessly integrates all of the functionality we need in the simplest and most contextual way. With this in mind, let’s review four trends that designers and developers would be wise to observe and integrate into their work so as to pave the way for a more holistic Web browsing experience:

  1. The browser as operating system,
  2. Functionally-limited mobile applications,
  3. Web-enhanced devices,
  4. Personalization.

[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.]

1. The Browser As Operating System

Thanks to the massive growth of Web productivity applications, creative tools and entertainment options, we are spending more time in the browser than ever before. The more time we spend there, the less we make use of the many tools in the larger operating system that actually runs the browser. As a result, we’re beginning to expect the same high level of reliability and sophistication in our Web experience that we get from our operating system.

For the most part, our expectations have been met by such innovations as Google’s Gmail, Talk, Calendar and Docs applications, which all offer varying degrees of integration with one another, and online image editing tools like Picnik and Adobe’s online version of Photoshop. And those expectations will continue to be met by upcoming releases, such as the Chrome operating system—we’re already thinking of our browsers as operating systems. Doing everything on the Web was once a pipe dream, but now it’s a reality.

Ubiquity

The one limitation of Web browsers that becomes more and more obvious as we make greater use of applications in the cloud is the lack of usable connections between open tabs. Most users have grown accustomed to keeping many tabs open, switching back and forth rapidly between Gmail, Google Calendar, Google Docs and various social media tools. But this switching from tab to tab is indicative of broken connections between applications that really ought to be integrated.

Mozilla is attempting to functionally connect tools that we use in the browser in a more intuitive and rich way with Ubiquity. While it’s definitely a step in the right direction, the command-line approach may be a barrier to entry for those unable to let go of the mouse. In the screenshot below, you can see how Ubiquity allows you to quickly map a location shown on a Web page without having to open Google Maps in another tab. This is one example of integrated functionality without which you would be required to copy and paste text from one tab to another. Ubiquity’s core capability, which is creating a holistic browsing experience by understanding basic commands and executing them using appropriate Web applications, is certainly the direction in which the browser is heading.

This approach, wedded to voice-recognition software, may be how we all navigate the Web in the next decade, or sooner: hands-free.

Map in Holistic Web Browsing: Trends Of The Future

Tracemonkey and Ogg

Meanwhile, smaller, quieter releases have been paving the way to holistic browsing. This past summer, Firefox released an update to its software that includes a brand new JavaScript engine called TraceMonkey. This engine delivers a significant boost in speed and image-editing functionality, as well as the ability to play videos without third-party software or codecs.

Aside from the speed advances, which are always welcome, the image and video capabilities are perfect examples of how the browser is encroaching on the operating system’s territory. Being able to edit images in the browser could replace the need for local image-editing software on your machine, and potentially for separate applications such as Picnik. At this point, it’s not certain how sophisticated this functionality can be, and so designers and ordinary users will probably continue to run local copies of Photoshop for some time to come.

The new video functionality, which relies on an open-source codec called Ogg, opens up many possibilities, the first one being for developers who do not want to license codecs. Currently, developers are required to license a codec if they want their videos to be playable in proprietary software such as Adobe Flash. Ogg allows video to be played back in Firefox itself.

4191027104 1b055821b0 O in Holistic Web Browsing: Trends Of The Future

What excites many, though, is that the new version of Firefox enables interactivity between multiple applications on the same page. One potential application of this technology, as illustrated in the image above, is allowing users to click objects in a video to get additional information about them while the video is playing.

2. Functionally-Limited Mobile Applications

So far, our look at a holistic Web experience has been limited to the traditional browser. But we’re also interacting with the Web more and more on mobile devices. Right now, casual surfing on a mobile device is not a very sophisticated experiences and therefore probably not the main draw for users. The combination of small screens, inconsistent input options, slow connections and lack of content optimized for mobile browsers makes this a pretty clumsy, unpredictable and frustrating experience, especially if you’re not on an iPhone.

However, applications written specifically for mobile environments and that deal with particular, limited sets of data—such as Google’s mobile apps, device-specific applications for Twitter and Facebook and the millions of applications in the iPhone App Store—look more like the future of mobile Web use. Because the mobile browsing experience is in its infancy, here is some advice on designing mobile experiences: rather than squeezing full-sized Web applications (i.e. ones optimized for desktops and laptops) into the pocket, designers and developers should become proficient at identifying and executing limited functionality sets for mobile applications.

Amazon Mobile

Amazon in Holistic Web Browsing: Trends Of The Future

A great example of a functionally-limited mobile application is Amazon’s interface for the iPhone (screenshot above). Amazon has reduced the massive scale of its website to the most essential functions: search, shopping cart and lists. And it has optimized the layout specifically for the iPhone’s smaller screen.

Facebook for iPhone

Facebook in Holistic Web Browsing: Trends Of The Future

Facebook continues to improve its mobile version. The latest version includes a simplified landing screen, with an icon for every major function of the website in order of priority of use. While information has been reduced and segmented, the scope of the website has not been significantly altered. Each new update brings the app closer to replicating the full experience in a way that feels quite natural.

Gmail for iPhone

Gmail in Holistic Web Browsing: Trends Of The Future

Finally, Gmail’s iPhone application is also impressive. Google has introduced a floating bar to the interface that allows users to batch process emails, so that they don’t have to open each email in order to deal with it.

3. Web-Enhanced Devices

Mobile devices will proliferate faster than anything the computer industry has seen before, thereby exploding entry points to the Web. But the Web will vastly expand not solely through personal mobile devices but through completely new Web-enhanced interfaces in transportation vehicles, homes, clothing and other products.

In some cases, Web enhancement may lend itself to marketing initiatives and advertising; in other cases, connecting certain devices to the Web will make them more useful and efficient. Here are three examples of Web-enhanced products or services that we may all be using in the coming years:

Web-Enhanced Grocery Shopping

Grocery1 in Holistic Web Browsing: Trends Of The Future

Web-connected grocery store “VIP” cards may track customer spending as they do today: every time you scan your customer card, your purchases are added to a massive database that grocery stores use to guide their stocking choices. In exchange for your data, the stores offer you discounts on selected products. Soon with Web-enhanced shopping, stores will be able to offer you specific promotions based on your particular purchasing history, and in real time (as illustrated above). This will give shoppers more incentive to sign up for VIP programs and give retailers more flexibility and variety with discounts, sales and other promotions.

Web-Enhanced Utilities

Grocery2 in Holistic Web Browsing: Trends Of The Future

One example of a Web-enhanced device we may all see in our homes soon enough is a smart thermostat (illustrated above), which will allow users not only to monitor their power usage using Google PowerMeter but to see their current charges when it matters to them (e.g. when they’re turning up the heater, not sitting in front of a computer).

Web-Enhanced Personal Banking

Grocery3 in Holistic Web Browsing: Trends Of The Future

Another useful Web enhancement would be a display of your current bank account balance directly on your debit or credit card (as shown above). This data would, of course, be protected and displayed only after you clear a biometric security system that reads your fingerprint directly on the card. Admittedly, this idea is rife with privacy and security implications, but something like this will nevertheless likely exist in the not-too-distant future.

4. Personalization

Thanks to the rapid adoption of social networking websites, people have become comfortable with more personalized experiences online. Being greeted by name and offered content or search results based on their browsing history not only is common now but makes the Web more appealing to many. The next step is to increase the user’s control of their personal information and to offer more tools that deliver new information tailored to them.

Centralized Profiles

If you’re like most people, you probably maintain somewhere between two to six active profiles on various social networks. Each profile contains a set of information about you, and the overlap varies. You probably have unique usernames and passwords for each one, too, though using a single sign-on service to gain access to multiple accounts is becoming more common. But why shouldn’t the information you submit to these accounts follow the same approach? In the coming years, what you tell people about yourself online will be more and more under your control. This process starts with centralizing your data in one profile, which will then share bits of it with other profiles. This way, if your information changes, you’ll have to update your profile only once.

Data Ownership

The question of who owns the data that you share online is fuzzy. In many cases, it even remains unaddressed. However, as privacy settings on social networks become more and more complex, users are becoming increasingly concerned about data ownership. In particular, the question of who owns the images, video and messages created by users becomes significant when a user wants to remove their profile. To put it in perspective, Royal Pingdom, in its Internet 2009 in Numbers report, found that 2.5 billion photos were uploaded to Facebook each month in 2009! The more this number grows, the more users will be concerned about what happens to the content they transfer from their machines to servers in the cloud.

Grocery4 in Holistic Web Browsing: Trends Of The Future

While it may seem like a step backward, a movement to restore user data storage to personal machines, which would then intelligently share that data with various social networks and other websites, will likely spring up in response to growing privacy concerns. A system like this would allow individuals to assign meta data to files on their computers, such as video clips and photos; this meta data would specify the files’ availability to social network profiles and other websites. Rather than uploading a copy of an image from your computer to Flickr, you would give Flickr access to certain files that remain on your machine. Organizations such as the Data Portability Project are introducing this kind of thinking accross the Web today.

Recommendation Engines

Search engines—and the whole concept of search itself—will remain in flux as personalization becomes more commonplace. Currently, the major search engines are adapting to this by offering different takes on personalized search results, based on user-specific browsing history. If you are signed in to your Google account and search for a pizza parlor, you will more likely see local results. With its social search experiment, Google also hopes to leverage your social network connections to deliver results from people you already know. Rounding those out with real-time search results gives users a more personal search experience that is a much more realistic representation of the rapid proliferation of new information on the Web. And because the results are filtered based on your behavior and preferences, the search engine will continue to “learn” more about you in order to provide the most useful information.

Another new search engine is attempting to get to the heart of personalized results. Hunch provides customized recommendations of information based on users’ answers to a set of questions for each query. The more you use it, the better the engine gets at recommending information. As long as you maintain a profile with Hunch, you will get increasingly satisfactory answers to general questions like, “Where should I go on vacation?”

The trend of personalization will have significant impact on the way individual websites and applications are designed. Today, consumer websites routinely alter their landing pages based on the location of the user. Tomorrow, websites might do similar interface customizations for individual users. Designers and developers will need to plan for such visual and structural versatility to stay on the cutting edge.

Conclusion

Each of these trends—browser operating systems, mobile, Web-enhanced devices and personalization—provides a foundation for the other. First, traditional browsers will continue to expand their functional scope to meet our demands, ideally in a way that simplifies the user experience rather than just by adding more tabs or toolbars. But our demands will ultimately drive mobile innovation as well, expanding points of entry to the Web far beyond our desks.

As people grow accustomed to being able to access the Web from anywhere, the next logical step will be to create unique entry points, specific to context and purpose and crafted especially for us. This final stage will be truly transformative, imbuing our daily lives with a rich layer of uniquely targeted information that will make us more efficient and effective in what we do. But reaching every step along the way will fully depend on the vision of designers and developers to refine existing interfaces and create completely new ones.

To Sum Up

  1. Web browsers will continue to be refined and expanded to include new functionality that will approach an operating system’s level of sophistication.
  2. Designers and developers need to become proficient at identifying and executing functionally limited sets for mobile applications.
  3. Previously unconnected objects will be enhanced with filters to send and receive contextual data across the Web. The design of these objects will change as a result of new interface attributes.
  4. Personalization trends will give users more control over their information and bring new, relevant information to them.

Further Resources

(al)


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

The JPG and GIF image file formats have their particular strengths, and both are common on the Web. So how do you decide which to use when your images contain type?

read more

TypeTalk: Type on a Curve

POSTED IN Blog, Tutorials | Comments Off

Setting type on a curving path can alter the balance and relationships between characters. Here's how to make sure your text still looks good.

read more

See our New Portfolio Items

We have been busy uploading new portfolio items onto our web site. Please take a look and check out some of our latest work. Be sure to let us know what you think.

Comments

    Archives