Leave a Comment

A Clockwork Box

March 2nd, 2010
Clockwork Orange cover
With CSS there are always various ways to accomplish something. After reading this short tidbit, you should be familiar with the various ways of controlling the size of an element’s padding, border, and margin, and you should know what the handy “clockwork” tip is, and how it will be useful to remember when you’re putting your CSS into practice.

Equal values on all four sides

If all four values (top, right, bottom, and left) are equal, then you simply write the following:

padding: 1px;
border-width: 1px;
margin: 1px;

The longhand way

If you don’t want equal values on all four sides, then you can specify each side individually:

padding-top: 1px;
padding-right: 2px;
padding-bottom: 3px;
padding-left: 4px;

border-top-width: 1px;
border-right-width: 2px;
border-bottom-width: 3px;
border-left-width: 4px;

margin-top: 1px;
margin-right: 2px;
margin-bottom: 3px;
margin-left: 4px;

The shortcut (like clockwork)

However this seems to be quite a hassle typing out each property, so you’ll find it’s much easier to use the following shorthand, which is in this order: top, right, bottom, left (think of the hands going clockwise around a clock). The following is equivalent to the above code:

padding: 1px 2px 3px 4px;
border-width: 1px 2px 3px 4px;
margin: 1px 2px 3px 4px;

Other shorthands

This is the style I find myself writing in most often, but there are two other shorthand styles you should be aware of:

padding: 1px 2px 3px;  /* top, left/right, bottom */
padding: 1px 2px;      /* top/bottom, left/right */

Summary

In short, there are various ways to define the padding, border, and margin on an element. Here’s a recap, with padding used as an example:

padding: 1px;              /* 1 value: top/right/bottom/left     */
padding: 1px 2px;          /* 2 values: top/bottom, left/right   */
padding: 1px 2px 3px;      /* 3 values: top, left/right, bottom  */
padding: 1px 2px 3px 4px;  /* 4 values: top, right, bottom, left */
Leave a Comment

Links for the week of February 21, 2010

February 28th, 2010

General links

Mobile

Leave a Comment

Links for the week of February 14, 2010

February 21st, 2010

General links

HTML5/CSS3 and new web technology

Mobile

Videos

BlackBerry showing off its new WebKit Browser

Engadget’s hands-on demo of Windows Phone 7 Series

Leave a Comment

Overall iPhone browser traffic share is decreasing (Jan2009 to Jan2010)

February 18th, 2010

According to the statistics available on statcounter.com, from January 2009 to January 2010, iPhone browser traffic share actually decreased, not increased, as one might expect.

This is likely due to new competition from Android phones, as well as the possibility that more users are simply using iPhone native apps instead of web apps.

In any case, in my opinion these are the figures we ought to be looking at, not overall phone sales, as others such as PPK concentrate on. If we don’t use computer sales as an estimate of desktop browser share, then why should we use phone sales as an estimate of mobile browser share? Just because someone has a phone with a pre-installed browser doesn’t lead them to actually use it.

In any case, here’s the statistics, with a few surprises:

  • iPhone/iTouch web traffic share decreased in the US and worldwide
  • BlackBerry gained market share
  • NetFront gained market share (this somewhat baffled me)

And now for the stats…

Worldwide mobile browser traffic (% share)

Device 2009 % 2010 % % change
Opera 24.69 25.53 +0.84
iPhone 23.06 21.52 -1.54
Nokia 17.78 18.53 +1.75
iTouch 12.89 11.6 -1.29
BlackBerry 4.91 9.85 +4.94
Android 1.92 4.54 +2.62
NetFront 1.35 3.27 +1.92
Sony PSP 4.38 1.2 -3.18
Openwave 2.61 0.97 -1.64
(Other) 6.41 2.98 -3.43

US mobile browser traffic (% share)

Device 2009 % 2010 % % change
iPhone 37.01 32.96 -4.05
iTouch 23.49 20.62 -2.87
BlackBerry 11.37 19.32 +7.95
Android 5.19 11.9 +6.71
Sony PSP 7.68 2.18 -5.5
Opera 3.56 3.06 -0.5
Openwave 3.07 2.04 -1.03
NetFront 1 2.26 +1.26
IEMobile 3.12 0.74 -2.38
(Other) 4.5 4.92 +0.42

Predictions for 2010:

  • Android continues to increase market share
  • Decrease in NetFront market share (opposite of current trend)
  • Microsoft Windows Phone 7 Series reverses downward IE trend
  • iPad grows in market share (this is a given, but will it break the top 10?)

Source: statcounter.com

Leave a Comment

Links for the week of February 7, 2010

February 15th, 2010

General links

Performance

Events

Leave a Comment

A primer on CSS colors

December 29th, 2009

Color keywords

Example usage:

// Example
body { color: red; }

// Generalization (not actual code)
body { color: color_name; }

Because color names are easy to remember, they’re handy for getting quick results, especially while doing rapid prototyping.

W3C’s CSS1 recommendation first mentioned 16 color keywords that you can use: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow:

Color Hexadecimal Color Hexadecimal Color Hexadecimal Color Hexadecimal
aqua / cyan #00FFFF gray #808080 navy #000080 silver #C0C0C0
black #000000 green #008000 olive #808000 teal #008080
blue #0000FF lime #00FF00 purple #800080 white #FFFFFF
fuchsia / magenta #FF00FF maroon #800000 red #FF0000 yellow #FFFF00

(color table from Wikipedia)

CSS2 officially mapped the colors to recommended hex values and also added the color orange. CSS3 removed orange, presumably because having 17 colors was aesthetically unpleasing in a binary world?

In addition to these 16 “official” colors, there’s even more unofficial color names you can use that appear to be supported in all the major browsers.

RGB values

Example usage:

// Example
body { color: rgb(255,0,0); }

// Generalization (not actual code)
body { color: rgb(red [integer 0-255], green [integer 0-255], blue [integer 0-255]); }

For this section it’s very handy to know a bit about color theory, particularly these facts:

  • all colors can be made from a combination of red, green, and blue (RGB) as the primary colors
  • in light (additive color mixing), the absence of all color results in the color black
  • in light (additive color mixing), the mixing of red, green, and blue in equal amounts results in the color white

With the rgb attribute, we specify the amount of each color we want with an integer from 0 to 255. Here we can see both black and white expressed as rgb values:

Black:
rgb(0,0,0)

White:
rgb(255,255,255)

Also note that if all three values are equal, there is no color that predominates and the result is a shade of gray.

Dark gray:

rgb(30,30,30)

A lighter shade of gray:

rgb(200,200,200)

And of course we can favor only one color, which in this case gives us a full red, with no green or blue:

rgb(255,0,0)

You may have guessed that we can also use percentage values to represent the same color:

rgb(100%, 0%, 0%)

RGBA values

// Example
body { color: rgba(255,0,0,0.5); }

// Generalization (not actual code)
body { color: rgb(red [integer 0-255], green [integer 0-255], blue [integer 0-255], alpha transparency [float 0-1]); }

CSS3 introduced rgba, which is in every way similar to rgb, except for the addition of a fourth value, alpha opacity, which gives us control over the transparency of the color.

So the equivalent full red we have above would look like this (no transparency):

rgba(255, 0, 0, 1)

rgba(100%, 0%, 0%, 1)

And the same color, only now semitransparent:

rgba(255, 0, 0, 0.5)

rgba(100%, 0%, 0%, 0.5)

Hex values

Example usage:

// Example
body { color: #ff0000; }

// Generalization (not actual code)
body { color: #rrggbb; }

Hex values are probably the most common out of all of the ways to represent colors in CSS. But I included them last – what gives? It seems to me that the rgb value should logically be explained first. The hex value is just a hex version (and thus slightly more confusing version) of expressing rgb values.

For this section you ought to know the basics of hexadecimal numbers. In particular, the fact that hexadecimals are base 16 and use letters a-f to represent numbers beyond our conventional base 10 range.

The hex value starts with a hash (#) and is followed by six numbers and/or letters. This is simply our three color values again: red, green, blue, with each color allowed two digits.

We express our solid red color like this:

#ff0000

As long as you can convert between decimal and hexadecimal (there’s a few free tools online), it’s relatively easy to convert between rgb and hex color values. Just keep in mind that the first 16 hex values are preceded by a zero (0 becomes 00, 1 becomes 01, 10 becomes 0a, 11 becomes 0b, etc.)

Shorthand hex

Example usage:

// Example
body { color: #f00; }

// Generalization (not actual code)
body { color: #rgb; }

Last but not least, if each rgb value has a repeating value, you can simply omit the repeating value. In the case above each of our color values was repeating (red = ff, green = 00, blue = 00), so we simply drop the repeating digit from each color and cut three bytes from our code:

#f00

A note on web-safe colors

Web safe colors were a recommended subset of about 256 colors with which to design websites. The rationale for solely using them for web design was for rendering consistency, so even users with very limited displays could see the page as it was intended to be displayed.

The concept of a “web safe” color was becoming obsolete even in 1997 or so, when I started making my personal website on AOL. It’s safe to say that the vast majority of users today are now able to view webpages with at least 16 million colors (256*256*256).

But this doesn’t mean we shouldn’t be concerned about colors. Apart from pure aesthetics, in the area of accessibility it’s often mentioned that users with colorblindness find certain combinations of colors difficult to see. So keep this in the back of your head when you go crazy with those wild color schemes!

More info

Probably the best way to learn how to use these color values is to actually try them on your website, however you might also find the following links useful.

Color Scheme Designer

Color Scheme Designer is a nice tool for finding several colors that (theoretically) should go well together. It’s a nice place to go when building a website from the ground-up.

http://colorschemedesigner.com/

Color Scheme Designer

Jonathan Schlaepfer made a nice helper tool built in Mootols for creating webkit gradients. Gradients wasn’t the subject of this entry, but it’s helpful to see a nice visualization of rgb values corresponding to the hex values.

http://schlaeps.com/mootools/gradient-creator/

Wikipedia: Web colors

HTML Colors

Leave a Comment

Video: John Resig – Testing, Performance Analysis, and jQuery 1.4

December 21st, 2009

In case you hadn’t seen it yet, John Resig was kind enough to stop by Yahoo! for the December Bayjax meetup. Here’s the video:

Usually developers are more interested in just getting the dang code to work, and as a result actual the testing and maintenance of JavaScript isn’t talked about too much, so I’m sure this will be new territory for many developers. And since it’s John Resig speaking, there was of course a bit about using TestSwarm, a testing distributed framework-agnostic automated testing tool (that’s a mouthful!).

Included in the talk are good things to note while testing, such as the fact unless you’re running Firefox or Chrome on Windows, all test times have a margin of error of up to 15ms (not to be confused with PPK’s observation of the delay between JavaScript computation and browser rendering).

(via YUIBlog)

7 Comments

PastryKit: digging into an Apple Pie

December 16th, 2009

Yesterday John Gruber wrote about Apple’s PastryKit, iPhone’s JavaScript framework that’s been discovered “in the wild” on the iPhone user guide at http://help.apple.com/iphone/3/mobile/. There’s a few ways to access the page:

  • with an actual iPhone or iTouch
  • by browsing with an iPhone/iTouch user agent. If you’re using Safari, enable the Developer menu in Safari>Preferences>Advanced and switching user agents by clicking on Develope>User Agent

What’s all the big fuss?

John was particularly interested in the responsiveness and native-like interaction of flinging through long lists, the fact the address bar is completely hidden, and the possibility of having a toolbar fixed to the top of the page. PastryKit makes all of these things possible and implements them better than anything else. And the result is nearly indistinguishable from a native app. Here’s a video I made of the iPhone user guide in action, powered by PastryKit. This is running on Safari – it’s not a native app!

PastryKit has been here for a while

As John Gruber points out, the code for PastryKit has been there for quite a while now. Stack Overflow has a question about it that was asked way back in July, and there are several more recent references to it by jQTouch developer David Kaneda on Twitter. Of course, since John’s post there’s been an explosion of interest in the form of even more tweets!

Hopefully with all of this increased attention, we’ll see Apple take notice and address it. Here’s hoping, anyway.

Some interesting features

There’s even more interesting takeaways from the PastryKit code, and I’m sure I’ve just barely scratched the surface:

  • implements its own form of Object-Oriented programming (obj.inherits and obj.synthetizes properties). When modules are declared, they’re registered as a PK Class (i.e. PKClass(PKBarButtonItem) registers PKBarButtonItem as a PK Class)
  • CSS3 wrapper functions (PKUtils.t() is a wrapper for translate3d, etc.)
  • no single library namespace (surprisingly) – which means there are many many global variables. This however is somewhat acceptable, as all variables are prefixed with “PK” and are declared to be constant (const PKStartEvent, const PKEndEvent) and cannot be overwritten.

There’s also some interesting takeaways not from PastryKit itself, but from the way the iPhone user guide is implemented. Most of the data on the page – including each menu icon (base64 encoded) – is located in a single 650kb JSON-encoded file called content.json. This means the initial loading of the page is quite slower than the user would normally expect, but once the initial payload has been delivered, it’s a relatively smooth browsing experience thereafter.

And as John Gruber already pointed out, this data is stored locally with the help of HTML5, allowing the user to continue reading even while offline!

iPhone user guide in Safari

iPhone user guide in Safari

PastryKit unminified and explained (sorta)

What I’m excited to show you now is a result of a bit of effort to make PastryKit more intelligible. Though there’s a minified version of the code on Apple’s website, it’s not obfuscated (and rendered unintelligible), so not all hope is lost! With the help of jsbeautifier.org we can now see the slightly unminified version of the code: PastryKit.js unminified.

The next thing I did was separate each module into its own file. I was able to separate the code into 27 numbered files, with the original ordering preserved (to prevent issues with dependencies). Viewing the code in this way definitely helps make sense of it all. You can download these separate files as part of a little unofficial SDK I made, which also includes a copy of the iPhone user guide with the JS iPhone-only redirect removed: PastryKit unofficial SDK.

PastryKit modules

The following is an explanation of each module I found. The descriptions are definitely incomplete and possibly inaccurate, so any comments or help is appreciated. But this should hopefully shed some light on the matter!

  • PKUtils – general helper functions (PKUtils.t() is a wrapper for CSS translate3d, PKUtils.degreesToRadians(), etc, etc.)
  • PKEventTriage – general event handler
  • PKPropertyTriage – handlePropertyChange() method – ?
  • Element – helper functions added to HTML Element prototype
  • Node – adds getNearestView() method to HTML Node prototype
  • PKClass – custom-rolled class with with “inherits” and “synthetizes” properties
  • PKObject – custom-rolled object with observer pattern. Most modules extend from this.
  • PKPoint – wrapper for WebKitPoint – used for touch events?
  • PKSize – wrapper for width/height properties
  • PKImage (inherits PKObject) – helper for creating Image elements and knowing when it’s finished loading (but doesn’t add the image to the DOM)
  • PKAnimator – basic animation tweens
  • PKTransition – helper for proprietary Webkit CSS transitions
  • PKTransaction – interacts with PKTransition – ?
  • PKView (extends PKObject) – manages a view, such as handling events that occur within that view – ?
  • PKContentView (extends PKView) – ?
  • PKRootView (extends PKContentView) – ?
  • PKScrollIndicator (extends PKView) – custom scrollbar
  • PKScrollView (extends PKView) – handles dynamically positioning the page when it’s scrolled
  • PKTableView (extends PKScrollView) – handles more touch/scroll events?
  • PKCellPath – ?
  • PKTableViewCell (extends PKView) – ?
  • PKToolbar (extends PKView) – manages the top toolbar
  • PKNavigationView (extends PKView) – manages bottom navigation bar
  • PKNavigationItem (extends PKObject) – manages bottom navigation buttons
  • PKControl (extends PKView) – manages generic controls
  • PKBarButtonItem (extends PKControl) – manages button controls
  • PKSearchBar.js (extends PKView) – manages the search bar

Conclusion after a first glance

As far as I can tell, this is no full-fledged JavaScript library. At least not for now.

On first glance PastryKit seems to be at most a nice development framework for making web apps with the same look-and-feel of native iPhone apps. And this framework in many ways does this better than anything out there (at the moment).

I echo the sentiments of Gruber – I do hope we hear more about this from Apple!

Leave a Comment

JavaScript tidbit: special variables ($, $$, _, etc)

December 8th, 2009

You’re probably used to typical variables names such as the following:

var personName = 'Joe';

You may not realize it, but there are some non-alphanumeric variables at your disposal.

Using $

For instance, the $ variable has been made popular by several JavaScript libraries, most notably jQuery. You can use it to alias operations that are commonly performed, such as the following (1):

var $ = document.getElementById;
var myElement = $('targetElement');

If you declare this variable outside of a function it will be a global variable and will compete with libraries that use the same global variable, so it’s probably best not to use it.

Interestingly, originally the dollar sign $ was originally intended for “mechanically generated code” (2), but as the usage of the symbol has become popular for other purposes, it looks like the latest version of JavaScript (ECMAScript 5th edition) now officially “oks” its use:

This standard specifies specific character additions: The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

Using $$

Some have come up with the solution of simply using two or more $$ symbols in order to distinguish the variable from libraries that just use a single $:

var $$ = document.getElementById;
var myElement = $$('targetElement');

Using _

You will find that you can use the underscore _ in the same way to alias variables and functions:

var _ = document.getElementById;
var myElement = _('targetElement');

Other symbols

If you’re really getting adventurous, you can even try using other symbols such as square root √, which seems to work just fine, just as $ and _ above. The only problem: it’s quite inconvenient using it, since it’s not available on any keyboards (except through some crazy key combinations perhaps).

Or you can put the symbol to use doing what you would naturally think it should do…

var √ = Math.sqrt;
alert(√(4));   // 2

References

(1) Even Faster Web Sites, p. 128
(2) Stackoverflow: Why would a javascript variable start with a dollar sign?

Leave a Comment

Ways of passing data to functions in JavaScript

December 4th, 2009

Passing data is quite important in functional programming languages like JavaScript. When there are multiple functions (which is most of the time), there needs to be a way to pass data between the functions. This is done by passing values in parenthesis: myFunction(myData). Even when there is no data to be passed, we still have to declare and execute functions by using parenthesis: myFunction().

Simple Passing

I’ve already referred to the common method of passing data. Here’s an example of the code in action:

function greeting (name) {
    alert('Hello ' + name);
}
var personsName = 'Joe';
greeting(personsName);  // Hello Joe

This example only passes one variable to the function. Note that we can get rid of the variable personsName and make the string on the fly. So the code above is equivalent to this:

function greeting (name) {
    alert('Hello ' + name);
}
greeting('Joe');  // Hello Joe

Ok. Now let’s suppose we have a function that accepts two variables:

function greeting (firstName, lastName) {
    alert('Hello ' + firstName + ' ' + lastName);
}
greeting('Joe', 'Schmoe');  // Hello Joe Schmoe

This doesn’t look too hard. But there’s a catch – the person writing the code has to remember the order of variables to pass in. Suppose they call the function like this:

function greeting (firstName, lastName) {
    alert('Hello ' + firstName + ' ' + lastName);
}
greeting('Schmoe', 'Joe');  // Hello Schmoe Joe

That’s no good! This isn’t the result we want. In the case of firstName and lastName the variable order isn’t too hard to remember, but in other cases the variables aren’t in any logical order, which can cause confusion.

No constructor overloading

Unlike other languages such as C++ and Java, JavaScript has no constructor overloading. In fact, JavaScript is (for better or worse) not even strict about enforcing the number of variables passed in. For example, the following code works fine and throws no errors, even though we’re not passing in a variable in the function call:

function test (someVar) {
    // do stuff
};
test();  // no errors!

It’s only when you try to use someVar within the function that causes the problems. Otherwise, everything’s working just fine and dandy.

What happens if we try the other case scenario: pass in more variables than the function expects? No errors again:

function test () {
    // do stuff
};
test('testing 123');  // again, no errors

And what happens if we try to declare a function with the same name? No errors, but the previous function is overwritten (this is generally to be avoided of course):

function test () {
    alert('First function');
};
function test () {
    alert('Second function');
};
test();  // Second function

Because JavaScript has no function overloading, all it takes to overwrite another function is to redeclare a function with the same name. It doesn’t matter what sort of arguments they accept.

Passing with the help of the arguments object

As it turns out, JavaScript has a handy arguments object to access the arguments passed into each function:

function test () {
    alert(arguments[0]);    // testing 123
};
test('testing 123');

In the above case the arguments object acts just as an array – it’s 0-indexed and can be used to access any arbitrary number of arguments. But arguments also has an interesting and useful property: length. Using arguments.length, we can traverse the array of arguments. This is handy in cases where we might want to add an arbitrary number of elements together:

function add () {
    var sumTotal = 0;                        // initialize total to 0

    for(var i=0; i<arguments.length; i++) {  // for each argument
        sumTotal += arguments[i];            // add current argument to total
    }

    alert(sumTotal);
};
add(2, 3, 4);  // 9
add(1, 1, 1, 1, 1, 1, 1, 1, 1);  // 9

Passing an object

JavaScript libraries such as YUI have already learned that the variable order is a common nuisance and an opportunity to introduce errors, so they’ve come up with a solution: pass a single object to the function. It ends up looking something like this:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
var nameObject = {};
nameObject.first = 'Joe';
nameObject.last = 'Schmoe';
greeting(nameObject);  // Hello Joe Schmoe

Now the variables become properties of a single object which is passed into the function. And it doesn’t matter which order the properties are declared in, which is a great relief to the developer.

Note that we can simplify the above code:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
var nameObject = {
    first: 'Joe',
    last: 'Schmoe'
};
greeting(nameObject);  // Hello Joe Schmoe

And we can simplify even further:

function greeting (obj) {
    alert('Hello ' + obj.first + ' ' + obj.last);
}
greeting({
    first: 'Joe',
    last: 'Schmoe'
});  // Hello Joe Schmoe

This is the form commonly used in these JavaScript libraries. It’s easy to copy-and-paste example code, but it might not always be so obvious what’s going on behind the scenes. You can see that just as we bypassed declaring a named variable in the Simple Passing model (with greeting(”)), here we use the same shortcut and bypass declaring a named object (with greeting({})).

call() and apply()

These two methods have different techniques for passing data to functions, but I’m going to have to hold off on them for now. It’s a bit complicated, since they’re only used to execute methods (functions) in other object contexts. But seeing as I need to explain object context to get into that, I’ll save that for a future entry!