Tuesday, December 16, 2008

Exploring Cross Document Communication

One of the new features that HTML5 offers web developers is a way to send information between documents on different sites via Javascript. Currently for security and privacy reasons, browsers prevent cross site scripting but with HTML5's Cross Document Messaging, the intention is to allow documents to communicate with each other without sacrificing security.

To experiment with these methods and events, you'll need to be running either IE8, Firefox 3 or the WebKit Nightlies. Opera 9+ provides support as well, but they use an older version of the spec which required the postMessage method to be called from the document object instead of the window object.

There are two key steps involved with HTML5 Cross Document Messaging. The first is posting the message. You do this by calling the window's postMessage() function. The postMessage function takes two arguments: the message to be sent, and the target origin.

Then, to receive the message in the other window, you need to watch for the window's message event using window.addEventListener or something similar. To help show how this works, I've set up an example for you to see here. In my example, both the sending window and the receiving window are located within the same domain (timkadlec.com), but as long as you have a reference to a window, you can communicate cross domain the same way.

Walking the Code


Take a look at the source code and you'll see that I'm simply using one window (window A) to open the other (window B) so that I have a reference to it. Window B contains two buttons that when clicked, use the postMessage method to post a message back to window A, like so:

  • window.opener.postMessage('John Smith', 'http://www.timkadlec.com');


We use window.opener to get our reference to window a, and then call the postMessage function and send the message 'John Smith' back to it. We specify that the origin is timkadlec.com in the targetOrigin argument.

Now back in window A, we need to prepare to receive the message. To do so, we look for the message event.

  • window.addEventListener('message', receiver, false);


As you can see above, I'm using addEventListener to listen for the message event, and once the event occurs, we call the receiver function.

  1. function receiver(e){

  2. if (e.origin == 'http://www.timkadlec.com') {

  3. if (e.data == 'John Smith') {

  4. alert(e.data);

  5. e.source.postMessage('Valid User', e.origin);

  6. } else {

  7. alert(e.data);

  8. e.source.postMessage('FAIL', e.origin);

  9. }

  10. }

  11. }


In the receiver function, we verify that the origin of the event is timkadlec.com (line 2). This is highly encouraged, as it ensures that we only receive messages from domains we are expecting to hear from. If you skipped this step, any domain could freely affect your page, and that could get a bit messy.

Then, we use the event's data property to retrieve the message that was sent. Based on the message received, we then use the source property of the event to obtain a reference to the window that sent the message. Then, again using the postMessage method (lines 5 and 8), we send a message back to window A.

This is a pretty straightforward example, and is really just meant to demonstrate how easy it is to post messages back and forth between documents. There's another good example up that makes use of iframes if you want to see another example of cross document messaging.

Some Security Considerations


Hopefully you can see that cross document messaging is both simple, and potentially quite useful for things like widgets, or authentication. However, there are some security risks if you don't take the time to double check a few things. First, like mentioned before, you should always double check the origin of the sent message. You don't want to be just accepting messages from anyone...that's kind of the reason cross-site scripting isn't allowed in the first place.

Secondly, it is possible to use the asterisk in the targetOrigin argument to allow your message to be posted to any domain. However, you should be sure to never use the asterisk symbol when sending confidential information. In those cases, you should be specifying the targetOrigin specifically so that you can guarantee that only the intended recipient gets the information.

Tuesday, December 2, 2008

Manageable CSS with CSSDOC

I've been very interested in finding better ways to create CSS stylesheets that are easy to navigate, understand and maintain. After leaving a stylesheet alone for awhile, if you didn't take the time to organize the stylesheet originally, it's really easy to forget why certain rules are being used, or where you defined styles for an area. One way of managing your stylesheets that's got my attention is CSSDOC.

CSSDOC was an idea apparently conceived sometime in 2007, and the Second Public Draft of the spec was just released on November 16th. The intent behind CSSDOC is to provide a standardized way of commenting CSS making use of the very well known DocBlock way of commenting source-code.

DocBlock is a very common form of documenting source code in programming that has proven to be very popular for both PHP and Javascript. The beauty of the method is that it's so simple to use DocBlock to organize your code and since it's a standardized format, other developers will be familiar with it and tools can be developed to parse it and auto-generate documentation.

There are a great deal of tags being developed for CSSDOC that can provide a lot of great information. For example, here is a sample header from the CSSDOC draft:

  1. /**

  2. * Homepage Style

  3. *

  4. * Standard Layout (all parts) for Big Little Homepage

  5. *

  6. * This style has been designed by Mina Margin. It reflects

  7. * the composition of colors through the years of the

  8. * customers project as well as the boldness it implies.

  9. *

  10. * @project Big Little Homepage

  11. * @version 0.2.8

  12. * @package xhtml-css

  13. * @author Mina Margin

  14. * @copyright 2008 by the author

  15. * @cssdoc version 1.0-pre

  16. * @license GPL v3

  17. *

  18. * @colordef #fff; white

  19. * @colordef #808080; standard grey

  20. */


Just by this simple header, we've already provided a great deal of information to both future developers and to a documentation parser. In our header we've provided the project we're working on, a version number for the project, copyright and author information, and some definitions of recurring colors used in the project.

You then make use of the @section and @subsection comments to divide your CSS file into manageable sections of related styles. I'd love to see this implemented in editors like CSSEdit's @group comment. For those of you unfamiliar, the @group comment in CSSEdit is parsed out and made into easy to navigate folders in the sidebar (see the image below).

CSS Edit - Screenshot

I won't go through all the available comments (the draft can give you that and does a great job of explaining), but suffice it to say there's a lot of extremely useful comments available: @affected comment which describes what browsers are affected by a certain bug/workaround; @tested comments to specify what browsers a certain section has been tested on; @fontdef for font definitions, similar to the @colordef rule in the example above; etc.

I'm very excited by this project and think the team behind the spec has done a fantastic job thus far. The few concerns I had, they've either addressed, or are in the process of doing so. It's very easy to get involved with the project as they have been very transparent in the development of the specification.

In addition, if you want to start playing around with CSSDOC a bit on your own CSS, there are bundles made already for editors like Textmate, EditPlus, and KomodoEdit just to name a few. You can keep up to date on new bundles and snippets at http://cssdoc.net/wiki/EditorIntegration.

Monday, October 27, 2008

Microsoft Gives Microformats a Little Oomph!

Historically, it hasn't been very often that I've been able to tip my hat to Microsoft for open web innovation. Today though is one of those times that I get to do so. John Allsopp, one of Microformats's biggest supporters, mentioned today that Microsoft's designer/developer community, Mix Online, has developed a IE toolbar called Oomph.

Oomph, much like Operator in Firefox, pulls microformatted information from a page and allows the user to make use of this data by offering options like being able to export contact information, map addresses, and add events to your calendar.

That would be enough in itself to get my attention...Microsoft has not typically been the most open of companies, and despite Gates' declaration that the web needs Microformats, they really hadn't done much to advance its' use. Seeing their developer community get behind Microformats with the toolbar and a couple of nice Microformats articles is very encouraging.

However, there's more to this story. In addition to the IE toolbar, a cross-browser Javascript implementation of Oomph was created. The toolkit, which makes use of JQuery, provides the same functionality of Oomph no matter the browser being utilized.

What's so wonderful about the way the Oomph toolkit functions is that the useful data is all right there in the browser window. Without the visitor leaving the site, they can grab a vcard of your contact information, see a listing of upcoming events, or make use of Visual Earth and view a map of a location.

This is, I think, a fairly major move. The beauty of Microformats is how easy it is to make your content more meaningful, and more useful. By providing similar data in a specific format, it significantly decreases the effort necessary to extract that data, and then use it. Having a cross-browser implementation of a script that makes use of this data to enhance its' functionality is really a nice feature and a great way to show off the value of using Microformats.

What's best is that since the toolkit makes use of Javascript and CSS for the effects and layout, we can modify the functionality and appearance for usage on our own sites. Technorati already offered services to help us extract contact information or event information, but the Oomph toolkit expands upon that functionality and allows us to offer even more enhanced options for visitors.

All in all, I am very pleased by this development. Microformats is such a valuable technology that is long overdue for mainstream implementation. It's nice to see yet another big supporter coming through to help it get there. Along with Technorati's tools and the fantastic Optimus Microformats transformer by Dmitry Baranovskiy, the resouces are in place and it should be interesting to see the ways these tools are utilized to provide a better user experience for visitors.

Sunday, October 19, 2008

Font Equality for Everyone

One of the areas that web design is lacking in, is a way to reliably provide beautiful fonts for our designs. There's a very limited amount of fonts that are actually safe to use on the web, because not everyone is a designer with lots of nice fonts installed on their machine. Sure, with font stacking we can help ease the pain a bit, but it's still a small amount of people that will see the fonts we intend, with everyone else getting boring alternates.

There are a few solutions currently being utilized across the web. The simplest, and also probably the worst option of them, is to use background images to display our custom fonts. This is not very ideal at all...every time we want to change the text on the site, we have to edit the appropriate background image. A couple less "needy" options are sIFR and FLIR. In both cases, Javascript is utilized to deliver the text in our desired font. sIFR uses Flash to make this happen and FLIR uses PHP. But we are still relying on Javascript to load the fonts onto the page, and there is some performance loss.

Thankfully, we are close to being able to make use of a CSS rule that makes font use so much simpler. The newest versions of all major browsers now support the @font-face rule, which gives us a lot of power over the fonts we can use in our sites. Unfortunately, some of them don't play too nicely yet. Firefox 3.1 and Safari both implement the @font-face rule very well, but IE only supports EOT fonts and I've found Opera 9.6's support is a bit unreliable. However, in the name of progressive enhancement, there's little reason why we can't start making use of this rule to improve our sites now.

Simply Powerful


The beauty of the @font-face rule is both how simple it is, and yet how powerful it is. The @font-face rule includes the rule and the font description like so:

  1. @font-face {

  2. }


The font description is made up of the what are called font descriptors. Simply put, they follow the same format of typical CSS style declarations. The most basic font description is composed of a font-family declaration and a src declaration that points to the font we will be using, like so:

  1. @font-face {

  2. font-family: "Benjamin Franklin";

  3. src: url(BenjaminFranklin.ttf);

  4. }


The url can be either remote or on your own site. However, for maximum browser compatibility, your font should reside in the same place as the page using it. Firefox, for instance, does not allow using fonts that don't have the same origin of the page. Instead of using a url, we can also use a local path ( local(font-path) ) that would point to a font located on the user's computer. We've now set the way for us to make use of the Benjamin Franklin font in our site.

  1. h1 {

  2. font-family: "Benjamin Franklin", serif;

  3. }


More Than Meets the Eye


Simple and easy. Here's where the fun stuff comes in though. Remember how those declarations, like the font-family declaration above, are called font descriptors? That's because they describe the declaration that can be used to trigger that font use. Admittedly, that might not be very clear, so let's extend our example:

  1. @font-face {

  2. font-family: "Benjamin Franklin";

  3. src: url(BenjaminFranklin.ttf);

  4. font-weight: all;

  5. }

  6. @font-face {

  7. font-family: "Benjamin Franklin";

  8. src: url(Hansa.ttf);

  9. font-weight: bold;

  10. }

  11. h1 {

  12. font-family: "Benjamin Franklin", serif;

  13. font-weight: bold;

  14. }

  15. h2 {

  16. font-family: "Benjamin Franklin", serif;

  17. font-weight: normal;

  18. }


In the example above, we changed the call to the font being used if the font-weight is bold. If the font-weight is anything but bold, then the Benjamin Franklin font is used. If the font-weight is set to bold, then the Hansa font is used. If you have Safari or the Firefox 3.1 beta you can take a look at the code in action. (NOTE: The only reason I was using two different fonts here is to make it obvious that the font is changed based on the font-weight. A more subtle example would be to use a variation of the base font, like a bold version.)

Descriptors give you significant power over the fonts you utilize. Instead of relying on the browser to fake a bold or italic version of the font, we can provide the more professional looking actual italicized, or bolded, version of the font, greatly improving the appearance of our design.

I highly encourage taking a look at the W3C's information on the @font-face rule and playing around with it a bit. There's some great examples of some of the powerful ways you can make use of the @font-face rules including an interesting example of redefining the basic serif font-family. Remember, for full functionality you'll need to either get ahold of Firefox 3.1 or Safari.

Keep in mind that not all fonts are meant to be used in this way. Some font providers encourage you to make use of their fonts freely, other's don't. So make sure you're allowed to make use of the font before embedding it on your site. Both fonts used in the examples, Hansa and Benjamin Franklin, are designed by Dieter Steffman who graciously allows his fonts to be freely used on the web.

Also, while there is a lot of power and control offered with the @font-face rule, still use it with some level of restraint. There is some time involved in downloading the font, so you should probably stick to using this method for headlines only...not body text.

Wednesday, October 15, 2008

Book Review: Mobile Web Development

Who Wrote It?


Mobile Web Development is written by Nirav Mehta, the head of Magnet Technologies a software development firm in India. He blogs about a variety of business and tech topics at www.mehtanirav.com.

What's Covered?


Mobile Web Development covers a wide variety of topics related to...guess what....mobile web development. Nirav does a fantastic job of introducing a wide variety of technologies needed to begin mobile web development including sending and receiving SMS and MMS messages, optimizing your site for mobile devices and using AJAX on the mobile web.

The book, from Packt Publishing, takes a very solution-based approach. Each chapter, with the exception of the first and last, has a very specific task that it is concerned with accomplishing. Usually, I'm not too awful fond of the format. It often feels like such books aren't teaching me a topic so much as giving me snippets of code I am comfortable with manipulating.

This book, however, is an exception to that rule. Each chapter, in addition to accomplishing the task at hands, takes the time to explain the possible solutions to the problem, and their pros and cons. The result is that once you've finished the book, you have a nice foundation of real working knowledge that will allow you to immediately get started with mobile web development. For those of us that may want a deeper understanding of the technologies, there are plenty of nods towards resources that will provide that information.

Should I Read It?


The book is intended for people with at least a basic understanding of CSS, Javascript and PHP. In particular, there is a fair amount of PHP code, so you should probably be comfortable with looking through it.

The book manages to cover a surprisingly large amount of information for being such a brisk read. The truth though, is that at least in the beginning, the basics of mobile web development are quite similar to the basics of web development, and you'll be pleasantly surprised by just how easy it is to get started.

One of the things I enjoyed most about Nirav's approach to the book is the emphasis on the user. Keeping the user in mind is always important, but particularly when the user needs to get the information quickly and needs to do it with a very small amount of screen real estate. Each chapter makes sure to mention how a given solution can help or detract from the user experience, ensuring that you have the understanding necessary to make good decisions that will benefit your users.

One Minor Complaint


The one and only issue I have with the book is that the editing could have been a bit better. Don't worry though, the editing is no-where near bad enough to confuse you. There's just a fair amount of a's and the's that are AWOL. Like I said, not enough to cause you trouble understanding the information, just enough that you'll notice.

Final Verdict


Mobile web development is one of the most important new avenues for web developers to pursue. The amount of people making use of mobile devices to get their information on the run is growing very quickly. Minor editing issues aside, the book was a great introduction to getting started with these technologies. I would highly recommend picking up the book and giving it a thorough reading. It's surprising how easy it is to get started in the mobile web, and after reading it you'll have a solid base of working knowledge to allow you to start creating your own mobile web content.

Great...Where Do I Get a Copy?


Thursday, September 18, 2008

The Canvas Element: Starting to Draw

Last time around, we took a general look at the canvas element and how it is supported (or not) in various browsers. This time, we'll start to go into the element in a bit more detail and start to look at some the things we can do with it.

A Quick Look at Attributes


We've already seen how to set up the canvas element in HTML:

You've probably noticed that we've included an id attribute on our canvas element to make it easier for us to access the element in our Javascript. You can also apply other standard attributes like class, title or tabindex. Two other attributes, height and width, will also be used fairly regularly.

You can define the height and width as attributes in the canvas element, or you can use CSS to define the dimensions of your element. If you use CSS, however, your canvas will scale to meet the dimensions you define instead of simply resizing the area. Neither height nor width are necessary, however. If you choose to not define the size of the canvas element, then it defaults to a size of 300 pixels wide by 150 pixels high.

Roll Up Your Sleeves...


All of this so far has been pretty easy...but also boring. The canvas element's real power, of course, is the ability to use Javascript to manipulate it. To do so, we have to get a rendering context using the getContext() function. The rendering context is what allows us to actually manipulate the content in the canvas element. The function is straight forward and easy to use:

  1. var canvas = document.getElementById('canvas');

  2. var context = canvas.getContext('2d');


Currently, "2d" is the only defined context that we can obtain. In the future, it is not unreasonable to expect to see that expand and include support for a three dimensional drawing context. Of course in a real-world setting you'll want to check to make sure the browser supports the getContext method in the first place. The canvas element is still relatively new and there will be a fair amount of browsers that will not support it.

The One and Only


Now that we have a rendering context, let's make use of it by starting to draw something to the canvas. The canvas element only natively supports one shape and that is the rectangle. Don't panic....you'll see later that there are plenty of methods available for us to create everything from a basic circle to very complex abstract shapes.

For now though, we'll keep it simple and just make a rectangle. We have three functions that are available to use for this: fillRect(), strokeRect(), and clearRect(). The functions do pretty much exactly what you would think based on their names. fillRect() draws a filled rectangle; strokeRect() draws a rectangle with border, or stroke, around it; and clearRect() clears the area and makes a fully transparent rectangle. To make it even more simple, each of the functions takes the exact same parameters. Let's take for example the following line of code:

  • context.fillRect(0,0,50,75);


As you can see, the function takes four parameters. The first two define the starting point of the shape, the x and y coordinates. Thankfully the coordinates follow common sense. The origin or (0,0) is the top left of the canvas element. So (0,10) would be at the top and 10 pixels from the left.

The next two parameters are the width and height of the canvas element. In this case, I made a rectangle that is 50 pixels wide and 75 pixels high. So the result of the above line of code is a 50 pixel by 75 pixel, filled rectangle in the top left corner of the canvas element. To get a good idea of the results of each of the rectangle functions, we'll use the following code (we've also set the height and width attributes on our canvas element to 125 pixels each) :

  1. context.fillRect(0,0,50,50);

  2. context.clearRect(25,25,50,50);

  3. context.fillRect(50,50,50,50);

  4. context.strokeRect(75,75,50,50);


The result, as you can see here, is four overlapping rectangles. Remember, you'll need Firefox (1.5+), Safari, or Opera (9+) to view it. As you can see, the clear rectangle clears out the area it covers. The stroke rectangle, on the other hand, doesn't clear out the area, so you can see the filled rectangle through it.

Next Time


Next time around, we'll start to look at some of the other functions available, and how we can use those functions to start making a variety of shapes...not just simple rectangles. To wet your appetite a bit in the meantime, have a look at another great example of how the canvas element can be used.

Wednesday, September 10, 2008

Getting Started with the Canvas Element

There's a lot of really exciting and interesting features arriving just around the corner in the world of web development. One of the new features that is receiving a lot of attention, and for good reason, is the new canvas element. The canvas element offers a lot of power to web developers, but can take a bit for some people to get comfortable with. So, I'm going to run a series of posts introducing this powerful new feature, and showing some of the ways it can be utilized.

What Is It, and Who Supports It?


The canvas element was originally implemented in Safari, and then became standardized in the HTML5 specification. The element allows developers to dynamically draw onto a blank 'canvas' in a website. Thankfully, you don't have to wait to play around with this element. Currently, you can find support for it in Firefox (version 1.5 and newer), Safari, or Opera (version 9 and newer). In addition, you can twist IE's arm a bit thanks to Google and Mozilla. Google has created ExplorerCanvas, a script that allows your canvas scripts to work in IE. For more intensive applications, Mozilla created has created an ActiveX plugin for IE to bring canvas support to the widely used browser. So, there's little reason why you can't start using it today....Google Maps does!

Unfortunately, there is some discrepancy in the way browsers support the canvas element right now. For example, in Safari, the canvas tag works a lot like the img tag...it doesn't require a closing tag. In Safari, you can close the element like so:

    In Firefox, however, the canvas element requires a closing tag:

      The problem comes in with alternate content. In Firefox, we can simply throw our alternate content in between the opening and closing canvas tags. If the browser doesn't support the canvas element, then the alternate content displays. In Safari, the content displays regardless. There are a few ways you can hack around this however, including this one presented by Matt Snider.

      Why It's Cool


      The canvas element is not meant for static images...though it can certainly be used to do that. The real power of it comes when we make use of Javascript to manipulate the canvas element and create dynamic visualizations like data charts and graphs, interactive diagrams and games. In fact, there are a couple impressive Javascript game recreations that have already been developed that make use of the canvas element. You can already play Mario Kart, Super Mario, and an incredibly addicting game called Ooze.

      The canvas element is a great example of where implementation precedes standardization. Safari implemented it, then Firefox and Opera caught on, and now the WHAT-WG is incorporating it into the HTML5 specification. Once implemented, it provides us with a standardized, cross-browser means to dynamically display data and react to user events in a way that previously required Flash.

      What's Coming Up


      Next time around, we'll start to look at the canvas element in more detail including the attributes available. We'll also start diving into some Javascript and some of the methods provided by the DOM to interact with the canvas element.

      Wednesday, August 20, 2008

      Living In Harmony

      The big news in the Javascript community for the last week has been the announcement of ECMAScript Harmony. A lot of news is really just overblown, but this is a big development, and one that any Javascript developer should be following.

      Some Background


      There's been a lot of talk in the Javascript community over the past 9 years or so about the development of ECMAScript 4, what was to be the foundation for what was being called Javascript 2. It was a controversial and fairly dramatic change from ECMAScript 3 (Javascript). There was going to be support for classes, inheritance, type annotations, namespaces...the whole flavor of the language was going to dramatically change.

      ECMAScript 4 was being developed primarily by Adobe, Mozilla, Opera and Google and was primarily based on the features those organizations wished to implement. Others, including Microsoft and Yahoo, found the proposed changes in ES4 to be to dramatic, and instead wanted to implement minor changes and bug fixes to ES3, labeling it ES3.1 instead.

      What Happened?


      Obviously with division among such major organizations, something was going to have to give. So, at a recent TC39 meeting (the committee in charge of developing the ECMAScript standard) met and a resolution was met. The two sides would merge their ideas together with a new committed focus to ensuring simplicity in the new changes to the language...enter ECMAScript Harmony. In an email, Brendan Eich of Mozilla laid down the 4 primary goals of ECMAScript Harmony:

      1. Focus work on ES3.1 with full collaboration of all parties, and target two interoperable implementations by early next year.

      2. Collaborate on the next step beyond ES3.1, which will include syntactic extensions but which will be more modest than ES4 in both semantic and syntactic innovation.

      3. Some ES4 proposals have been deemed unsound for the Web, and are off the table for good: packages, namespaces and early binding. This conclusion is key to Harmony.

      4. Other goals and ideas from ES4 are being rephrased to keep consensus in the committee; these include a notion of classes based on existing ES3 concepts combined with proposed ES3.1 extensions.


      What Does It Mean?


      Well, for one, it means that the series of posts I had started on Javascript 2.0 are now completely worthless...and no...I will not reimburse you for the time spent reading them.

      But far more importantly, it means that progress should speed up immensely. (There are ES4 proposals from 1999.) The plan appears to be to implement certain de facto standards rather quickly. For example, getters and setters are already implemented in each of the major browsers except for IE, and they will be thrown into the ES Harmony specification. (Which, by the way, brings up the interesting situation where implementation precedes specification, something that occurs often on the web and something you'll probably see me talk more about in the future.)

      Meanwhile, ActionScript 3.0 was already built to reflect the ECMAScript 4 proposed specifications...so it would appear they're kind of left a bit high and dry. It sounds as though they are definitely committed to keeping in line with specifications, and that they plan on implementing new features laid out in the newly developed specification. They are also going to continue to keep their current features, like classes and type annotations, available in their language...think of it as an extension to the ECMAScript standard.

      My Thoughts


      All in all, I think the outcome is positive. ES4 had been taking forever to get going, and ES3.1 hadn't been sounding like it would do much besides fix bugs. Now, we'll have a new implementation soon and while it won't have the same dramatic changes ES4 had in mind, there will be some interesting new features being added.

      While I would've enjoyed some of the new features, Javascript gets to maintain a lot of flexibility here. ES4 would've tightened that up a bit, and I still haven't really made up my mind on whether that would've been a good thing or not.

      It's also quite encouraging to see so many major players working together. Microsoft, Yahoo, Google, Mozilla, Opera and Adobe all working together in harmony. (I apologize for the pun...it was just there, and I decided to go with it.) One can only imagine having these organizations working together will ensure a high quality specification, and also lead to faster implementation of the spec.

      Around the Web


      This is certainly a huge development, and there has been no shortage of postings about it. There's a lot of high quality discussion going on by some major players in the world of Javascript and ActionScript, and I highly recommend checking them out.

      Tuesday, August 12, 2008

      Undermining the Industry

      <rant>

      It's no secret that the web design industry is often not given the respect it deserves. People treat it as if it's a much simpler task than it really is. Forgive me if I come off sounding a bit arrogant, but it seems like people seriously underestimate the work involved in creating a quality web site.

      One issue, for example, is people expecting to see comps of work without payment. It happens quite a bit, but it's a ridiculous request. Do people ask mechanics to make the first couple of repairs on their car for free so they can get a feel for how they like working with them and then, based on that, decide whether or not to go with that mechanic and pay them? So why ask a web design company to create a few mock-ups first before deciding to actually pay them for their work?

      Then there's beautiful journalism like the article posted yesterday in the Wall Street Journal telling companies how to build their own site with 8 hours of work and $10. Brilliant...because that's all that goes into a quality site.

      Really, there are some fantastic gems in the article like this one:
      All you need to know is that a block of HTML essentially, a bunch of gobbledygook words and symbols can add extra features to your site.

      And this isn't some second-fiddle publication being read by 5 people, this is the Wall Street Journal. A highly regarded and professional publication.

      So where does all this undermining come from? It think a lot of it stems from a lack of understanding. For almost as long as there has been the web, there have been "build-your-own site" tools easily and readily available. This gives people the feeling that that's really all it takes...a couple clicks of a button, drag a few things, and you have a site.

      But the reality, as we all know, is that there is so much more that goes into the design and development of a site. So much more planning and "strategerizing" goes into the process. Can you build your own site with these free tools? Yes. Should you? That really all depends on how serious you are about making your website a business tool. If you really want to maximize it's impact, then the answer is probably no.

      I understand I'm preaching to the choir a bit here, but after coming across Jeff Croft's link to the WSJ article, I just had to vent a bit. It's sad to see such a lack of understanding and respect of our industry come from such a well-known and highly regarded paper.

      </rant>

      Monday, August 11, 2008

      New Way to Store Custom Data

      There's a lot of interesting new features being suggested for HTML5 and XHTML2. Some of them are extremely useful, some of them seem to be more questionable additions. One feature being implemented in HTML5 that I do like is the addition of custom data attributes to HTML elements.

      Manage Your Data


      A custom data attribute is simply any attribute starting with the string "data-". They can be used to store data that you want kept private to the page (not viewable by the user) in cases where there is no appropriate attribute available. Every element can have any number of custom data attributes.

      For example, consider a form validation script. The script needs to know what form of validation is required for each field. Currently, many of these scripts will use the class attribute to signal that.




      Making use of the new HTML5 custom data attributes, we might choose to store the information like this instead:




      To gain access to the value of the data-validation attribute, there are two options. First, you can simply use the getAttribute() method. This method should be familiar to anyone who's worked with the DOM in Javascript and is supported by all major browsers. The second method is to make use of the new dataset DOM attribute. Currently, no major browsers support the dataset attribute, but to be fair, here's how you would use it:

      1. var theInput = document.getElementById('myInput');

      2. var validationType = theInput.dataset.validation;


      What I Think


      Custom data attributes have been met with varied opinions...some think it's fantastic while others either don't get the value or simply don't like the idea. Personally...I think it's a good idea.

      Currently there's two popular ways of providing hooks for scripts in HTMl where no appropriate attribute exists:

      1. Use an existing attribute even though it may not necessarily be semantically correct.

      2. Create a new attribute and have the page no longer valid.


      Where you stand personally along those lines, of course, varies. Some people don't mind a page that doesn't fully validate and would rather not clog up their id's and classes. Others don't mind adding an extra class to an element as long as the page is valid.

      With the new data-* attributes, you can have the best of both worlds; your page can validate and you don't have to add extra classes and id's to make your scripts work. It's also very easy to implement, and manages to keep all the data needed for scripting together in one dataset. What's not to like?

      You can actually start making use of custom data attributes right now. The page won't validate for HTML4 of course, but once HTML5 rolls around you'll be set. Just remember that to access the dataset values in Javascript you will need to use the getAttribute() and setAttribute() methods as the dataset DOM attribute is not currently supported.

      Sunday, August 3, 2008

      Excuses, Excuses

      I did what I said I told myself I would never do...I only posted one item the entire month. I always told myself that if I was going to have a blog going, I was going to commit to it and ensure that the blog never went stale...there would always be fresh content on my site. I think I may have underestimated the wonderful curves that life throws out there!

      I do have what I feel are a few fairly good excuses for being quiet lately. I just recently purchased my first home, which my wife and I are quite excited by. It has kept us both busy moving and making some quick touch-ups and improvements. Even more exciting, we found out that my wife is pregnant with what will be our first child. Again...extremely excited, but I am finding that I am spending a fair amount of time ensuring that things are in place for when the little one arrives.

      Finally...I started a new job in June. It's much more development heavy than my prior position and I'm enjoying it greatly. That being said, there was some time spent ensuring that I get up to speed with the company's existing projects and work styles. Nothing irritates me more than knowing that I could do something much quicker if I had a better handle on things. I don't like that "introductory period" where I have to turn to ask questions about simple little procedures simply because I don't know the company's tendencies, so I like to get familiarized as quickly as possible.

      So between those three things, all exciting as they are, I have had very little time for updating the site. Which is unfortunate...I've been working on getting the site switched over to PHP and have some cool and important improvements that will come with this (one of which is an improved comment spam filter....those spammers are amazingly persistent).

      There are also numerous posts I have written up that I just need to take the time to add to the site. So the content is there...or, I guess, will be there. The resolution for August is to get back to a regular schedule for updating the site...so stay tuned.

      Monday, July 14, 2008

      Improving Web-Ed

      One topic that I have been interested in for quite some time now is secondary education when it comes to web development and design. It is a very unfortunate truth that when it comes to web development, the curriculum is in serious need of some help.

      As a recently graduated student, I can reflect on both my training and the training of other people my age who attended other colleges for web development that I interacted with. Unfortunately, the majority of the people I've communicated with stated the same thing: standards based development was not presented as a priority. CSS was glossed over and there was little to no mention of the DOM and unobtrusive scripting techniques in the Javascript courses.

      Why Colleges Can't Keep Up


      A large part of this is due to the fact that our industry moves so quickly. Progress is made at such an incredible pace and new technologies soon emerge while old ones fade away. In contrast, changing the curriculum at a college usually takes awhile, making it very difficult for schools to keep up.

      Another issue is that some of the best candidates for taking on the role of instructor in these courses are overlooked due to a lack of degree. It would be great to have industry-tested professionals teach the courses...who better to teach a class about the techniques and tools that will be necessary in the field than those who are doing it, and have been doing it for some time.

      That is not meant to be a criticism of all current instructors. As always, there are exceptions to the rule. There are industry professionals who have no place standing in front of a class and teaching technique, and likewise there are instructors who do a fantastic job of presenting their classes with quality information. And many of the other instructors simply have their hands tied by what the college allows them to do and not do.

      One thing I do like seeing is that a few instructors who are pushing standards-based development forward in their courses have published their class information. Daniel Mall and William Craft are just two examples of people who are pushing forward with standards based development instruction and then sharing with others what they are doing. This opens the door for critiquing from industry professionals and provides an example of what other instructors might consider basing their coursework around.

      How Do We Fix It


      So what needs to be done? Universities and colleges need to adjust. Traditional methods of updating curriculum simply do not work when it comes to such a fast-paced industry. These institutions need to be making a concerted effort to keep their curriculum up to date with current industry standards, and as a result, the curriculum should be re-evaluated on a very regular basis.

      In the mean time, a temporary fix may be to implement some sort of a rotating course, a generic web development study course. The course could be used to highlight emerging industry standards and could rotate on a semester basis. Again, just a temporary fix, but at least it provides a small level of attention to the techniques that the students will be needing.

      I'd also like to see a few schools start taking a look at allowing existing professionals to instruct more courses, regardless of higher-education degree status. There is a lot of insight they can offer and it's a shame that schools are not tapping into that.

      Of course, that door swings both ways. I'd love to see us as professionals get more involved in helping colleges to evaluate and update their curriculum. I applaud Opera and the people behind their new Web Standards Curriculum. If you haven't seen it yet, take a look. They are putting together a series of 50 articles or so highlighting areas in web design and development. This is exactly the kind of thing that can really help colleges by providing a guideline for what to build their new curriculum around.

      Let Me Hear Your Thoughts


      This is a topic that interests me very much. Eventually I would love to start teaching a bit myself...I love sharing what I've learned with others and find the teaching experience to be very rewarding. That is why I pay attention to what the current colleges are doing to try and stay ahead of the game a bit. I would love to hear any input you might have on the topic. Trying to improve web education in colleges is not an easy task and I think getting more opinions and discussion on the matter are exactly what is needed to come up with a better way to help get colleges up to speed and keep them there.

      Thursday, June 26, 2008

      Elsewhere on the Web

      Test Driven Development


      There was a nice article at Sitepoint about Test Driven Development. The author, Chris Corbyn, walks through the TDD process using PHP examples, and describes some of the benefits he has discovered in the TDD process.

      Firefox 3 Memory Benchmarks and Comparison


      With both Firefox 3 and Opera 9.5 being freshly released, here's a nice memory performance comparison of those browsers, as well as the IE Beta version 1 and Flock. The memory tests are computed by a custom built .NET application, and provide a good look at how these browsers compare in memory management on the Windows operating system.

      Sketching in Code: the Magic of Prototyping


      The folks over at A List Apart offer us yet another excellent write-up. David Verba, Technology Advisor for Adaptive Path, takes a look at using prototypes in the web application development process, and what prototyping can offer that wireframes cannot.

      Same DOM Errors, Different Browser Interpretations


      Hallvord R. M. Steen of Opera offers a very interesting look at how the different browsers interpret the DOM, and what tools each of them provide for debugging. Some attention is also given to Opera's new debugging tool, Dragonfly.

      Tuesday, June 17, 2008

      A Better Way To Globalize

      Lately I've been working quite a bit with some PHP code that made heavy use of global variables. It made the code quite rigid to work with...when changes were made in one function it had a ripple effect on many other key functions and more than once, made me curse global scope.

      But sometimes it's necessary to share information between different functions, so what's a programmer to do? Global variables certainly make that possible, but they also create some problems. Heavy reliance on global variables makes it difficult to reuse code. Rarely can we uproot functions with a large dependency on global variables and insert them into different contexts or scripts without problem.

      Debugging code also becomes difficult. When a variable is global in scope, it could be being instantiated virtually anywhere making it tough to track down. What's even worse is coming back to that code after a year, or as it was in my case, trying for the first time to decipher code that relies on global variables.

      Luckily there's a much better way: the registry pattern. The registry pattern simply creates a class that servers as a central repository, or registry, of objects that we can now utilize throughout our code. It accomplishes this by utilizing static methods and properties, which means you'll want PHP5 to accomplish it....you can use it in PHP4 but it requires some workarounds. This pattern is particularly useful when used to store a data connection.

      Breaking It Down


      The best way to explain this is to walk through the code.

      1. class Registry{

      2. private static $instance;

      3. static function instance(){

      4. if ( ! isset( self::$instance ) ){

      5. self::$instance = new self();

      6. }

      7. return self::$instance;

      8. }

      9. }


      The code above first simply creates our registry class, aptly called Registry (line 1). We then create a static function (line 3) and variable (line 2). This is how we will keep track of whether or not an instance of this class exists. If it doesn't, then we create a new instance of the class.

      Now we just need to create set and get functions for anything we want to use globally. In this case, we'll create set and get functions for a very simple object that we'll call a TestObject and a variable to contain that object.

      1. class Registry{

      2. //.....

      3. private $testObject;

      4. function getTestObject(){

      5. return $this->testObject;

      6. }

      7. function setTestObject( TestObject $test){

      8. $this->testObject = $test;

      9. }

      10. }


      Our two new methods do exactly what they sound like...the get and set methods simply retrieve or save our testObject to the $testObject variable. That's all there is to it...now we can use our registry class to make a TestObject instance that we can use globally (for this post, just accept that TestObject allows us to set and display a message...all the code is available for those who want a closer look). Since we are using a static property and method to ensure that all instances of that class have access to the same values, it doesn't matter where we initially instantiate the class.

      1. function setting(){

      2. $myTest = new TestObject();

      3. $myTest->setMessage ( "Registry Patterns Rock!" );

      4. $reg = Registry::instance();

      5. $reg->setTestObject( $myTest );

      6. }

      7. function retrieve(){

      8. $reg = Registry::instance();

      9. $myObject = $reg->getTestObject();

      10. echo ( $myObject->getMessage() );

      11. }

      12. setting();

      13. retrieve(); //outputs Registry Patterns Rock!


      Now despite the fact that we create the two instances of the registry class within two separate functions, you can see that they both have access to the same values thanks to the Registry pattern, without all the mess that can be caused by global variables. To add more values to our registry class, we simply add more private variables and some set and get functions.

      But Wait...There's More!


      Another handy way of utilizing the registry pattern, is to use our Registry instance to create and then cache an object, skipping the need for a set or get function. For example, if I have a data connection that I know I want to be standard throughout the project I can create a function like this inside of my Registry class:

      1. class Registry{

      2. //.....

      3. function dataConn(){

      4. if ( ! isset ( $this->dataConn ) ) {

      5. $this->dataConn = new dataConn();

      6. $this->dataConn->setHost( 'localhost' );

      7. }

      8. return $this->dataConn;

      9. }

      10. }


      Now, instead of worrying about the set and get functions, I can just call the dataConn() function. If the data connection has already been created, then it returns the connection. If not, it first creates my connection, and then returns it. So I can safely call the function without concerning myself with whether or not I've already created the connection...it takes care of that for me.

      The registry pattern is so incredibly useful and a definite improvement over using the dreaded global variable in your code. I highly encourage you to play around with the sample code and see the different ways that the registry pattern can manage your code.

      Wednesday, June 4, 2008

      Javascript: The Good Parts

      Who Wrote It?


      When I first heard Douglas Crockford was writing Javascript: The Good Parts (let's just call it JTGP from here on out) I was anxiously awaiting the release. Crockford has been responsible for many highly regarded articles and presentations, as well as for his incredible work with JSON, JSLint and much more. While Brendan Eich may be the father of Javascript, Crockford is probably the Godfather. Even Eich himself called Crockford "the Yoda of Lambda JavaScript programming."

      What's Covered?


      JTGP does as promised...it brings to attention the best parts of the Javascript language. Topics like Objects, Inheritance, Arrays, Functions and Regular expressions are discussed throughout the book. While focusing on the "good parts" of Javascript, Crockford also points out the not-so good parts and explains why these other parts don't fall into the good category by pointing out caveats and pitfalls.

      I've seen it mentioned before that people complained about the book being a bit short. It weighs in at a very light 145 pages, 45 of which are appendixes. The information is quite dense however, and I thought the appendixes were extremely valuable. The appendixes include looks at what Crockford considers to be the "awful parts" and the "bad parts" of Javascript. They also include looks at JSLint and JSON as well as providing some helpful syntax diagrams.

      Should I Read It?


      As mentioned before, the book is short, but very dense. As a result, there is a lot of information covered, but not always a lot of explanation involved. The book seems to take a bit of a different approach than the typical Javascript book...it's more focused on why than it is on how.

      That is not at all a bad thing though. Assuming you have a nice handle on the language and it's syntax, there is a lot to get out of reading this book. In fact, there is so much information crammed in here that it will probably take several readings to truly grasp all the information being delivered. Don't make the mistake of assuming that because it is short it is an easy-read...this book covers advanced information and does so at a very rapid pace.

      The Final Verdict


      JTGP is a great book for anyone who wants a deeper understanding of the why behind the how. I would recommend it to anyone, though I would warn that you'll want to have a decent understanding of the syntax before reading it...since the book focuses so much on why, there's not a lot of explanation on how things work, and to get all that this book has to offer, you'll want to know that. Overall, a very good book that is good enough to demand several readings.

      Great...Where Do I Get a Copy?


      Wednesday, May 21, 2008

      Libraries and Frameworks

      A question I get asked often through emails and other discussions is how I feel about frameworks and libraries, both for scripting and for CSS. I've been meaning to share my thoughts on it for awhile, and now that I see NetTuts.com has posted an article about choosing a CSS framework, I figured now is as good a time as any.

      Any of you who have been reading my site since the beginning might remember I wrote a post about the importance of forcing yourself to reinvent the wheel. I still stand by that, but that doesn't mean I am entirely against all frameworks. In fact, in the case of scripting libraries, I can definitely see the value in using them. The key point is to be able to tell when to use a library and when not to.

      Why Should You?


      One nod for using libraries and frameworks is that reusable code is a good thing. It saves you time and money, and I think most developers have at least some amount of code that they reuse on various projects. I am all for that. We programmers are lazy...errr...efficient. If we can create a solution that is flexible and reusable...then more power to us.

      Libraries are also quite handy in large teams. They provide a common base for everyone on the team to start from, and if you stick to a certain naming or formatting convention, in combination with a library of some sort (either in-house developed or not), you can make communication very easy and eliminate a lot of the questions that can arise when passing code from developer to developer.

      Large applications also provide us a good reason to use a library. In Javascript, for example, there are a fair amount of browser incompatibilities. These incompatibilities are taken care of by most Javascript libraries, allowing a developer to focus on developing the actual logic for the application not the browser differences that arise.

      On the Other Hand...


      There are many issues though that can arise from consistent use of libraries and frameworks. If you use a library exclusively, you can become quite dependant on it. It's important to understand the underlying code that the library is using. If you continue to depend entirely on a library to cover all browser bugs for you, there will come a time when there will be a bug it doesn't cover, and you aren't going to know where to turn to troubleshoot it.

      Also, and this is particularly true in CSS frameworks, you can become too attached to what the framework provides and start conforming your code to fit in with the framework or library you are using. There is a saying that goes "When the only tool you have is a hammer, everything looks like a nail." If you are using a CSS framework to create your layout and there is a particular visual style that the framework doesn't quite get right, the most common approach, unfortunately, is to conform to the framework. You start to look for ways to make the layout fit within the frameworks provided structure.

      Continuing with CSS frameworks, there is also a definite lack of semantics. You end up with mixing content with presentation by providing HTML markup that uses classes like yui-gb or span-8. I understand that semanticity is not no everyone's top 10 list of important things to do (though I do feel it should be a priority). But if semantics aren't particularly important, why not just use tables to mark up the page. It would take less code and would work almost seamlessly browser to browser. (Please note, I am not in any way condoning the use of tables for layout...I'm just making a point.)

      For those Interested


      So, in case you're wondering...here's where I stand on using libraries and frameworks. For Javascript, I occasionally use a library for code, usually on larger apps. Most of my code though is hand-created, however I do try to build with reusability in mind. I guess you could say I have my own personal library that I use.

      As far as CSS goes...I don't use frameworks and can't see a time where I will actually do so. The lack of semantics rubs me the wrong way and to be honest with you, most of my CSS is not that similar from site to site. That being said, I have used reset styles of some sort on most projects, and there are a few other basic styles that I tend to include on all of my CSS, but it's no more than a few lines. It doesn't take me particularly long to get a layout set up in CSS, so I don't feel like a framework would help increase my efficiency in doing so.

      That last paragraph sounds a bit harsh...but hopefully you understand that that's just one man's opinion. Again, I am not opposed entirely to frameworks and libraries; in fact as I said above I have used Javascript libraries in particular on more than one occasion. I just think it's important that frameworks are used only when appropriate and as enhancements to your coding abilities...not the foundation for them.

      Saturday, May 17, 2008

      Behavior in Your Presentation

      I've spent some time lately playing around with the WebKit Nightly Build. In addition to having advanced CSS support, the nightly build also introduces a few new proprietary CSS properties (though the plan is to eventually get W3C to implement them in the CSS specification). There are some really cool features being implemented, including CSS gradients, masks and transforms. One new feature, CSS transitions, has me a little on the fence though.

      CSS transitions are definitely a cool idea. Using one simple line of CSS, we can specify how we want a particular style to change. For example, a very common thing to do with CSS is change a link's color when hovered over. To do so, you just use the :hover pseudo-class like so:





      1. a{

      2. color: blue;

      3. }

      4. a:hover{

      5. color: red;

      6. }



      Browsers make the color change immediately when a user hovers over the link. Using WebKit's transition property, we can tell the browser to instead make a smooth transition. For example, to make the color slowly change from blue to red over the course of two seconds, we could do the following:





      1. a{

      2. color: blue;

      3. -webkit-transition: color 2s linear;

      4. }

      5. a:hover{

      6. color: red;

      7. }



      We tell the browser (line 3) what style we want to animate (color), for how long (2s) and what kind of transition we want to use (linear). If you have the WebKit nightly build, I set up an example using the CSS above. It works great, and the transition is super smooth. Better yet, the other browsers just disregard it and perform the color change as usual. Simple and cool right?

      Mixing Things Up a Bit


      The problem I have with it is that it I think it starts to put CSS in our behavior layer, which is not so cool. Remember, one of the major benefits to proper use of web standards is being able to separate our content, presentation and behavior onto their own separate layers. By using CSS to make these changes, we make it difficult to interact with these properties using Javascript. Will we have access to information regarding how far into the animation we are? Will the transition fire some sort of onFinish method? Javascript would be needed to add this level of flexibility...not CSS.

      While looking around for more information, I was happy to run across a post from late 2007 by Jonathan Snook that shares my opinion on the matter. One thing Jonathan suggested was that while browser animation is not a bad idea perhaps it should have been an extension to the DOM instead. That would offer more robustness and flexibility, and seems to preserve the separation of concerns a bit better.

      Don't get me wrong...I'm very excited about most of the new features on display in the nightly build. I can also see how the line between behavior and presentation is a bit blurred already. After all, isn't :hover a bit of a behavioral style? I just think that given the potential interactivity here, I have to agree with Jonathan and say that adding a method to the DOM would make more sense in this case.

      Saturday, May 10, 2008

      Elsewhere on the Web

      line-height: abnormal


      Eric Meyer has a great write-up about how diverse the rendering of line-height: normal is across browsers. Complete with a test page that allows you to see what happens to the value of line-height normal as different fonts and font-sizes are selected.

      What's Next in jQuery and JavaScript


      John Resig of jQuery fame posted a nice 11 minute video where he talks about what is coming up for jQuery, Javascript, and some changes that are being made in browsers. Nice overview of what we have to look forward to on all counts.

      Initial Impressions of Silverback


      A nice review of Silverback, the new user testing development tool created by the geniuses over at Clearleft. Personally, I haven't had a chance to play with it yet, as it is only available for Macs and I am still laboring away on a PC. From everything I've heard though, looks like a fantastic tool.

      Content Inventory


      Just a bit more Clearleft love here. Andy Budd continues his series of posts looking at design artifacts with a look at the value and importance of performing a content audit.

      UserVoice


      Finally, though I'm a bit late on mentioning it, I'd be remiss if I didn't say something about the release of UserVoice, home grown here in Wisconsin. UserVoice allows you to provide a way for users of a site, application, anything really, to discuss and vote on changes and features. In addition to being useful right out of the box, there are some cool additions to the product being looked at like OpenId support and perhaps an API.

      Sunday, May 4, 2008

      Not As Clear As It Seems: CSS3 Opacity and RGBA

      One of the many things CSS lets us control is the opacity of elements, starting in CSS3. The opacity property is in fact one of the earliest and most widely implemented CSS3 properties. It has its problems though, but CSS3 also defines a more powerful way to control an element's transparency: RGBA values.

      The Opacity Property


      To change the opacity of an element using the opacity property, you simply give it a value between 0 and 1 to determine the elements' opacity. For example, if I want a div to be 50% transparent, I would give it the following style:





      1. div {

      2. opacity: .5;

      3. color: #fff;

      4. background-color: #000;

      5. }



      This works fine in Safari, Opera, and Firefox. Internet Explorer, however, doesn't yet support the opacity property. Instead, we have to use their proprietary property Alpha Filter. It's really not any more difficult than the opacity selector. One key thing to note hear though is that the Alpha Filter requires you specify the opacity on a scale of 0 to 100. There's even a catch to that though...the element is that you are applying the opacity filter to has to have a hasLayout value of true. While there are many ways of making an element have layout, some of the most common are to set a width, or give the element a zoom value of 1. So now our declaration is as follows:





      1. div{

      2. background: #000;

      3. opacity: .5;

      4. filter: alpha(opacity='50');

      5. zoom: 1;

      6. }



      Simple enough...but with one catch that may or may not present a problem, depending on your situation. When you use the opacity property, the opacity is set for that element, and any children of that element. This can cause problems in readability and general appearance. If you do have problems in this situation, you may not have to resort to a PNG just yet.

      More Power


      CSS3 also allows for an extended version of the RGB color model that includes a fourth value that is used to specify opacity. Again, like the opacity property, the alpha value in the RGBA model accepts a value between 0 and 1. We can use an RGBA value anywhere that colors values are accepted in CSS: borders, background, font colors, etc. This already offers a higher level of control than the opacity selector.

      Even better yet, while the opacity property defines the opacity for an element and all of its children, using the RGBA value only applies that transparency to the given property of an element that we specify. For example:





      1. div{

      2. background-color: rgba(0,0,0,.5);

      3. color: #fff;

      4. }

      5. <div>

      6. Some white text.

      7. </div>



      Using the background-color property and assigning an RGBA value to it, we are able to define the transparency for the divs' background color. The transparency of any text or elements inside of the div is unchanged. In contrast, using the opacity property, the paragraph above would inherit the 50% transparency defined on the div.

      Unfortunately, as is often the issue, browser support for RGBA is limited. Both Safari and Firefox 3 offer support for the RGBA color value system, but so far Opera and IE do not. The good news though, is that we can use the RGBA value without worrying about it breaking our design by also defining a fallback color.





      1. div{

      2. background-color: rgb(0,0,0);

      3. background-color: rgba(0,0,0,.5);

      4. color: #fff;

      5. }



      In most browsers that do not recognize RGBA values, that declaration is simply ignored, as it should be. In IE though (I know, surprise, suprise), it appears that RGBA values cause IE to not display the background at all. A way to get around this would be to use conditional comments to reset the background to a solid color for IE. So we can just define a solid color for browsers that do not accept RGBA values and leave the transparency for those that can support it...a prime example of progressive enhancement.

      I have set up a working comparison of RGBA versus using the opacity property for you to view in each browser. Remember, to see the effects of RGBA, you will have to view the page in Safari or Firefox 3.

      Monday, April 28, 2008

      An Objective Look at Javascript 2.0: Strong Typing

      In our first look at the new features of Javascript 2.0, we will focus on the new typing system. We are just going to highlight some of the major changes and potential uses. For a more detailed look, take a look at the ECMAScript 4.0 Language Overview.

      Traditionally, Javascript is a loosely-typed language, meaning that variables are declared without a type. For example:






      1. var a = 42; // Number declaration

      2. var b = "forty-two"; // String declaration




      Since Javascript is loosely typed, we can get away with simple 'var' declarations...the language will determine which data type should be used. In contrast, Javascript 2.0 will be strongly typed, meaning that type declarations will be enforced. The syntax for applying a given type will be a colon (:) followed by the type expression. Type annotation can be added to properties, function parameters, functions (and by doing so declaring the return value type), variables, or object or array initializers. For example:






      1. var a:int = 42; //variable a has a type of int

      2. var b:String = "forty-two"; //variable b has a type of String


      3. function (a:int, b:string)//the function accepts two parameters, one of type int, one of type string


      4. function(...):int //the function returns a value with a type of int




      NOTE: There has been some confusion about enforcing type declarations so I thought I'd try to clear it up. Enforcing type declarations simply means that if you define a type, it will be enforced. You can choose to not define a type, in which case the variable or property defaults to a type of 'Object' which is the root of the type heirarchy.

      Type Coercion


      Being a strongly typed system, Javascript 2.0 will be much less permissive with type coercion. Currently, the following checks both return true:






      1. "42" == 42

      2. 42 == "42"




      In both cases, the language performs type coercion...Javascript automatically makes them the same type before performing the check. In Javascript 2.0, both of those statements will resolve to a 'false' value instead. We can still perform comparisons like those above; we just need to explicitly convert the data type using type casting. To perform the checks above and have them both resolve to 'true', you would have to do the following:






      1. int("42") == 42

      2. string(42) == "42"




      While adding a strongly typed system does make the language a bit more rigid, there are some benefits to this change, particularly for applications or libraries that may be worked with elsewhere. For example, for a given method, we can specify what kinds of objects it can be a method for using the special 'this' annotation. I'm sure there are many of you who just re-read that sentence and are scratching your heads trying to figure out what the heck that meant. An example may help:






      • function testing(this:myObject, a:int, b:string):boolean




      The method above accepts two arguments, an int and a string. The first part of the parameters (this:myObject) uses the this: annotation to state that the function can only be a method of objects that have the type of 'myObject'. This way if someone else is using code we have created, we can restrict which objects they can use that method on, preventing it's misuse and potential confusion.

      Union Types


      We can also use union types to add a bit of flexibility. Union types are collections of types that can be applied to a given property. There are four predefined union types in Javascript 2.0:






      1. type AnyString = (string, String)

      2. type AnyBoolean = (boolean, Boolean)

      3. type AnyNumber = (byte, int, uint, decimal, double, Number)

      4. type FloatNumber = (double, decimal)




      In addition, we can set up our own union types based on what we need for a particular property:






      • type MySpecialProperty = (byte, int, boolean, string)




      One final thing I would like to mention is that in contrast to Java and C++, Javascript 2.0 is a dynamically typed system, not statically typed. In a statically typed system, the compiler verifies that type errors cannot occur at run-time. Statically typing would catch a lot of potential programming errors, but it also severely alters the way Javascript can be used, and would make the language that much more rigid. Because JS 2.0 is dynamically typed, only the run-time value of a variable matters.

      Thursday, April 24, 2008

      Phantom CSS

      At the heart of CSS, of course, are its selectors. They are after all what allow us to apply styles to a given element in our (X)HTML. Sometimes though, there is a desire to apply a style based on an elements state. That is where pseudo-classes come into play. You've probably all used them at some point...but there may be more there than you realize. Their value makes it worth taking a closer look.

      Static Pseudo-Classes


      Pseudo-classes allow us to apply an invisible, or "phantom", class to an element in order to style it. For example, let's look at the element most often styled using pseudo-classes: the anchor tag (). Some anchor tags point to locations a user has already viewed, and some point to locations the user has not yet visited. Looking at the document structure, we can't tell this. No matter if the link is viewed or not, it looks the same in (X)HTML. However, behind the scenes, a "phantom" class is applied to the link to differentiate between the two. We can access this "phantom" class with pseudo-class selectors, like :link and :visited. (Pseudo-classes are always prefixed by a colon.)

      The :link pseudo-class selector refers to any anchor tag that is a link...that is any anchor tag that has a href attribute. The :visited pseudo-class selector does exactly what it sounds like...it refers to any link that has been visited. Using these pseudo-classes allows us to apply different effects to links on the page according to the visited state.





      1. a {color:blue;}

      2. a:link {color: red;}

      3. a:visited {color: orange;}



      The above styles for example, will make any anchor tag that does not have a href attribute to be colored blue (line 1). Any link that has a href attribute, but has not been visited will be red (line 2). Finally, if a link is visited (line 3), then it is an orange color.

      Another static pseudo-class is :first-child (The :first-child pseudo-class is not supported by IE6). The :first-child selector is used to select elements that are first children of other elements. This can be easily misunderstood. A lot of times, people will try to use it to select the first-child of an element. For example:







      1. Here is some text




      Say we want to apply a style to the paragraph element. It is not uncommon to see people try to do this using the following style:





      • div:first-child {font-weight: bold;}



      However, this is not how the pseudo-class works. If we think back to the concept of pseudo-classes essentially being "phantom" classes, then what we just did was apply a phantom class to the div like so:







      1. Here is some text




      Obviously that is not what we want. The :first-child selector doesn't grab the first child of an element; it just grabs any of the specified element that is a first-child. The correct way to style that would be with the following line:





      • p:first-child {font-weight: bold;}



      That's probably as clear as mud, so it may help to take another look at the "phantom" class:








      1. Here is some text






      Watch Your Language


      Corny headings aside, we can select elements based on the language using the :lang( ) pseudo-class. For example, we can italicize anything in French using the following style:





      • *:lang(fr) {font-style: italic;}



      Where does the language get defined? According to the CSS 2.1 specification, the language can be defined in one of many ways:
      In HTML, the language is determined by a combination of the lang attribute, the META element, and possibly by information from the protocol (such as HTTP headers). XML uses an attribute called xml:lang, and there may be other document language-specific methods for determining the language.

      Dynamic Pseudo-Classes


      So far, what we have discussed are static pseudo-classes. That is, once the document is loaded, these pseudo-classes don't change until the page is reloaded. The CSS 2.1 specification also defines three dynamic pseudo-classes. These pseudo-classes can change a document's appearance based on user behavior. They are:

      • :focus - any element that has input focus

      • :hover - any element that the mouse pointer is placed over

      • :active - any element that is activated by user input (ex: a link while being clicked)


      Usually, these pseudo-classes are applied only to links. However, they can be used on other elements as well. For example, you could use the following style to apply a yellow background to any input field in a form when it has the focus.





      • input:focus {background: yellow;}



      The main reason this is not done a lot is because of a lack of support. IE6 does not allow any dynamic pseudo-classes to be applied to anything besides links. IE7 allows the :hover pseudo-class to be applied to all elements, but doesn't let the :focus pseudo-class be applied to form elements.

      Complex Pseudo-Classes


      CSS offers us the ability to apply multiple pseudo-classes so long as they aren't mutually exclusive. For example, we can chain a :first-child and :hover pseudo-class, but not a :link and :visited.





      1. p:first-child:hover {font-weight: bold;} //works

      2. a:link:visited {font-weight: bold;} //link and visited are mutually exclusive



      Again, there is a compliance issue here with IE6. The IE6 browser will only recognize the final pseudo-class mentioned. So in the case of our first style above, IE6 will ignore the :first-child pseudo-class selector and just apply the style to the :hover pseudo-class.

      Looking Forward to CSS3


      In addition to the pseudo-classes laid down in CSS 2.1, CSS 3 provides sixteen new pseudo-classes to allow for even more detailed styling capabilities. The new pseudo-classes are:





      • :nth-child(N)

      • :nth-last-child(N)

      • :nth-of-type(N)

      • :nth-last-of-type(N)

      • :last-child

      • :first-of-type

      • :last-of-type

      • :only-child

      • :only-of-type

      • :root

      • :empty

      • :target

      • :enabled

      • :disabled

      • :checked

      • :not(S)





      For more information about the new pseudo-class selectors laid down in CSS3, take a look at the
      CSS3 selectors working draft, or the excellent write-up by Roger Johansson. Currently, very few have decent cross-browser support, but as Johansson says, they can still be used for progressive enhancement...and in such a quickly changing field, when we can stay ahead of the curve, we should take advantage of it.

      Tuesday, April 22, 2008

      An Objective Look at Javascript 2.0: Looking Back

      There has been no shortage of debate over Javascript 2.0, based on ECMAScript 4.0. Some people are extremely excited about some of the new features being discussed, and some feel that Javascript 2.0 is shaping up to look a bit too much like Java or even C++ for their tastes.

      Whether you like the new features being proposed, think they're silly and unnecessary, or have no idea what the heck I am talking about, I think it's important to have a firm grasp on some of the changes being proposed. Doing so will help you to better understand both sides of the debate, and also help to prepare you for when Javascript 2.0 becomes available for use.

      There's far too many changes and fixes to discuss them in one post, so this will be an ongoing serious of posts. I'll be taking a look at what the new language provides us and why. Hopefully by taking a closer look at all the changes, we can get a better feel for how those changes affect both web developers and javascript in general. First though, we should take a quick look at how Javascript got to this point, and the reasoning behind the changes beings suggested in Javascript 2.0.

      Once Upon a Time...


      Javascript has been around since 1995, when it was debuted in Netscape Navigator 2.0. The original intent was for Javascript to provide a more accessible way for web designers and non-Java programmers to utilize Java applets. In reality though, Javascript was used far more often to provide levels of interactivity on a page...allowing for the manipulation of images and document contents.

      Microsoft then implemented Javascript in IE 3.0, but their implementation varied from that of Netscape�s and it became apparent that some sort of standardization was necessary. So the European Computer Manufacturers Association (ECMA) standards organization developed the TC39 committee to do just that.

      In 1997, the first ECMA standard, ECMA-262, was adopted. The second version came along a bit later and consisted primarily of fixes. In December of 1999, when the third version rolled out, the changes were more drastic. New features like regular expressions, closures, arrays and object literals, exceptions and do-while statements were introduced, greatly adding value to the language. This revision, ECMAScript Edition 3, is fully implemented by Javascript 1.5, which is the most recently released version of Javascript.

      Like ECMAScript 3, the proposed ECMAScript 4 specification will provide a very noticeable change in the language. As it stands now, Javascript 2.0 will be featuring, among other changes, support for things like scoping, typing and class support.

      Let the Debate Begin


      While some of the changes are bug fixes, the justification for the major revisions appears to be largely based on providing better support for developing larger-scale applications. With the growing popularity of AJAX, and the rise of RIAs, Javascript is now being used for much larger-scale apps than it was ever intended for. The proposed changes to ECMAScript 4 are intended to help make development of those kinds of apps easier by making the language more disciplined and therefore making it easier for multiple developers to work on the same application.

      This is where the debate starts....how much do we need these revisions? Technically, we can implement a lot of the same kinds of structures using the language as it stands currently. The proposed changes are aimed at making that easier, but there are some people who worry about the effect this may have on what is currently a very expressive and lightweight language.

      Which group is correct? Are the changes going to make our lives as Javascript developers easier, or force us to lose a lot of what makes Javascript such an attractive scripting language to use today? I think the only way to really judge how the changes will affect us is to take a closer look at the changes themselves and see both the good and the bad.

      Wednesday, April 16, 2008

      Spring Cleaning

      Overall, I've been quite happy with the feedback gotten about the site so far. It's still quite young however, and therefore, there are a few changes that I thought needed to be made to help it continue to grow, and hopefully make it easier for readers to find and use the content here. For anyone interested, I thought I would highlight the changes.

      First off, I've increased the focus on past posts. I decided to add a listing of the latest posts to each page, as well as a listing of the most popular posts on the site in terms of views. The idea here is to hopefully make it easier for you to find earlier posts that you may have missed that may still be worth a look.

      I also decided to add full RSS feeds. I have heard a lot about the debate between partial and full feeds and wasn't sure at first how to proceed with them. Up to now, I had just been offering partial feeds. I am still keeping those, for any of you who do prefer them but I am also offering an RSS feed with the full posts in them now for those of you who prefer to have the entire article in front of you.

      One new area in the footer is a listing of the galleries that were gracious enough to link to my site. I was overwhelmed by the positive response to the design of the site, and those galleries are how quite a few of you first came across the site. I thought I would finally get around to returning the favor by supplying some links back to them.

      Finally, I decided to embed by Twitter status into the site. I fought the Twitter urge until March, but once I finally gave in, I've become fairly addicted. It's a makes it easy to keep connected with people who you may not converse with a whole heck of a lot otherwise, and if you are following the right people, it can be quite the news informant...lots of tech news seems to hit Twitter before anywhere else. To sum it up, you could do a lot worse for a networking tool.

      Now, with all the new additions, something had to go to clear up some room. So, I decided to pull the "Things I Learned Online" section. Actually, I've wanted to do something different with that anyway, and this made for a good excuse. By only showing a couple links at a time in the side, I felt that some of the articles and tools I come across probably weren't getting the attention they deserve given their quality. I wanted a way to highlight a few more at a time, and to do it in a way that brings a bit more attention to them.

      So after much hemming and hawing I decided to occasionally post a small group of links to resources, articles and tools that I have found that I think may interest you. Don't worry...I'm not going to turn into a site that posts nothing but lists of other sites, nor am I going to start doing a whole bunch of Digg-made top 10 posts. The bulk of the posts here are still going to be the same kind of content you've been seeing with focuses on technical, design, and theoretical articles...I'll just occasionally throw some focus out to other articles that I think are worth a read.

      Having said all that (that was a bit more long-winded than intended), I'm always interested in improving the quality of what my site has to offer. So, if anyone has any strong opinions about any new changes (good or bad), or has some other ideas they'd like to see implemented (content or just enhancements), let me know.

      Sunday, April 13, 2008

      It’s Good to Be Wrong

      Being wrong is a good thing. I know...I know...we've been told our entire lives that it's better to be right than wrong. I think, though, that in the design/development industry, it's good to be wrong sometimes.

      Always being right means we're not challenging ourselves enough. It means that either we've become comfortable and content with where we are at with our skills, or that there is no one challenging us to improve those skills. In either case, we're not progressing.

      If we're wrong, it means we're pushing ourselves to explore our limits, to continue to expand our skill set. Being wrong opens the door for constructive criticism, which in turn leads to opportunities to learn. People who are willing to tell us when we're wrong are the kind of people we should be surrounding ourselves with...they're the kind of people who challenge us to become better designers and developers.

      One quote, that I believe sums it up pretty well, is by Bill Buxton a Principal Researcher at Microsoft. In his book "Sketching User Experiences", Bill has the following to say:
      People on a design team must be as happy to be wrong as right. If their ideas hold up under strong (but fair) criticism, then great, they can proceed with confidence. If their ideas are rejected with good rationale, then they have learned something. A healthy team is made up of people who have the attitude that it is better to learn something new than to be right.

      While Bill's quote is aimed at designers, I think the rule applies to both designers and developers. Making mistakes, getting constructive criticism, and learning from that criticism is a healthy thing. It allows us opportunities to expand our skills and grow in our field. Only through this kind of healthy criticism can our skills, and ultimately the products we produce, become finely tuned.