Tag Archives: web development

Recommended open source docs

Programming books and documentation on shelfHaving written a fair bit of technical documentation, this tweet requesting recommendations for the best open source docs caught my eye:

Thankfully lots of people were keen to suggest good examples and six hours later I went through the replies. The variety was surprising, from man pages to tutorials to core modules so well written you “don’t really need documentation to understand it”! In the end, there were a few that got several mentions so for the record, here are the open source docs that were recommended at least twice, with one clear winner:

Photo by Niels Heidenreich: https://www.flickr.com/photos/schoschie/1330790063/

Song: Oh! Selector ♪

Downloads

Get high quality versions of this song from iTunes and Bandcamp.
Also, free not-quite-so-high quality downloads are available from SoundCloud and Last.fm.

Lyrics

Now when I was a young boy startin' out in this industry
I remember this pearl of wisdom that the internet gave to me.
To manipulate or decorate something on a web page
First ya gotta grab it and there's pretty much just one way...

[Chorus]
Oh selector, oh won't you fetch for me
With your magic sense, all the elements within the old DOM tree.

Now selectors can be used in CSS, oh but there's more.
In plain ol' JavaScript as well with querySelector().
And don't forget the libraries like jQuery and so
You could say that they're essential if you wanna be a pro.

[Chorus]

The next step on your journey is to learn selector syntax.
There's not much to remember so don't worry, just relax.
You start with a plain ol' tag name if you want it to be styled,
Use "plus" for adjacent sibling and "greater than" for a child.

[Chorus]

A dot is for a class name and for IDs it's a hash.
Use square brackets for attributes and you're sure to find a match.
Now :hover needs a colon like :focus and :target.
There's other stuff as well but that's enough to get you started.

[Chorus]

One final word of warning for my song to be complete.
Remember please that all IDs have got to be unique.
They're bad 'n' they're mean and they don't fight clean and you're gonna find it tough
If you use more than one of each because this DOM ain't big enough.

[Chorus x 2]

Responsive is not just visual: Three useful web APIs

A mobile user using a laptop outside.Mobile users are on the go. They’re rushing to get a train or busy meeting people. They don’t have much time and they’re on a slow connection. Right?

The answer of course is not necessarily. So-called mobile browsing could include shopping online while tucked up in bed, sending messages while watching TV or giggling at silly photos while relaxing in a cafe. It could also include being out and about but not using a mobile device.

In reality we have no idea what the users of our website are doing or where they are, and it would be a huge invasion of privacy if we did! Our fancy responsive designs should therefore not only look good but also be flexible enough to handle a variety of situations.

In other words, responsive doesn’t mean responding to screen size or even device capabilities. It means responding to the user’s environment (as much as possible).

But enough chatter. How can we do this in practice?

There are three handy web technologies that take us part of the way there: the Battery Status API, the Network Information API and Ambient Light Events. Support for all of them is mostly Chrome and Firefox for now, but keep an eye on caniuse.com and mobilehtml5.org for the latest support info. And now, on to the APIs…


Battery Status API

Why use it

Knowing whether your user is plugged in or not and whether their battery has much juice left can influence how your site reacts. Battery-draining features such as repeated actions and animations can be reduced or disabled, for example. Or you could notify the user and offer to save the current state in case there’s a sudden shutdown.

How to use it

The spec had a rewrite recently and now uses shiny new promises. The advantage of this is that the API is asynchronous, meaning that when you call the getBattery() method the browser makes sure the BatteryManager object is ready before you try to read its attributes. Those attributes are:

  • charging (a boolean)
  • chargingTime (in minutes)
  • dischargingTime (in minutes)
  • level (a number between 0 and 1)

Each of these attributes has an event so you can listen for when they change. In practice, you could use the attributes and events like this:

// Prepare a function to display the battery status
function showStatus(battery) {
  battery.onchargingchange = function () {
    console.log('Charging: ' + battery.charging);
  };
  battery.onchargingtimechange = function () {
    console.log('Charging time remaining (mins): ' + battery.chargingTime);
  };
  battery.ondischargingtimechange = function () {
    console.log('Discharging time remaining (mins): ' + battery.dischargingTime);
  };
  battery.onlevelchange = function () {
    console.log('Battery level: ' + battery.level);
  };
}

// Check for browser support first
if (!!navigator.getBattery) { // The latest API is supported
  // Use the battery promise to asynchronously call showStatus()
  navigator.getBattery().then(function(battery) {
    showStatus(battery);
  });
} else if (!!navigator.battery) { // The old API is supported
  var battery = navigator.battery;
  showStatus(battery);
}

Guille Paz has made a nice battery status demo which includes code for the old and new versions of the spec.

Status

This API has the best support of the three with Opera, Chrome and Firefox having implemented it. In the case of Firefox, the implementation currently uses an old version of the spec so for the time being it’s best to allow for both versions in your code.


Network Information API

Why use it

You’re probably aware of the navigator.onLine HTML5 attribute and its wide browser support but that only tells us if the user is connected to a network or not. For more detailed information about the network we need the aptly-named Network Information API. With the data it provides you could opt to show smaller or lower-quality images to users on slow connections, or only show a video background when you know the network speed is fast. Be careful when making assumptions though — wifi doesn’t necessarily mean fast.

How to use it

When fully implemented this provides the type and speed of connection using two attributes (type and downlinkMax) on the global navigator object. Let’s jump straight into an example…

// Some browsers use prefixes so let's cope with them first
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

// Check for browser support
if (!!connection) {
  // Get the connection type
  var type = connection.type;

  // Get the connection speed in megabits per second (Mbps)
  var speed = connection.downlinkMax || connection.bandwidth;
}

So easy! The type values are a pre-defined selection of self-explanatory strings:

  • bluetooth
  • cellular
  • ethernet
  • none
  • wifi
  • wimax
  • other
  • unknown

Network speed, when available, is exposed as downlinkMax, previously called bandwidth, although in reality this is difficult for browsers to measure so it may be a while before we’re able to use it. You can also attach a change event listener to navigator.connection to be even more responsive.

For a more thorough look at this API and its background, Aurelio De Rosa has written a good tutorial and network information demo which I recommend.

Status

In the browsers I tested only connection.type was supported properly and that was only in Chrome for Android and Firefox Mobile/OS (you may need to ensure dom.netinfo.enabled is set to true). It’s still early days for this API but its simplicity means it could easily be incorporated into your website or app.

Note: There is a version of the spec hosted on w3.org that currently says work on it has been discontinued. This refers to an older version and current work is being done in the GitHub-hosted version, which should eventually migrate to the W3C site.


Ambient Light Events

Why use it

We’re probably all familiar with struggling to read a screen in bright sunlight. Increasing the contrast of what’s displayed on the screen or hiding distracting backgrounds can make content much easier to read in such cases. The opposite is true — reducing how vivid a design is can avoid users screaming and covering their eyes when in a dark environment.

How to use it

Tomomi Imura, AKA @girliemac, has the definitive lowdown on how to respond to differing levels of light. Eventually we’ll all be able to use CSS4 media queries so when the light-level is dim, for example, we can respond accordingly. In the meantime though, there’s the more precise JavaScript approach which gives you access to data from the device’s light sensor. You just listen for a devicelight event and use that event’s value attribute to get the brightness of the user’s surroundings measured in lux. For example:

window.addEventListener('devicelight', function(e) {
  var lux = e.value;

  if (lux < 50) {
    // ambient light is dim so show lower-contrast version
  }
});

See Tomomi's article for a more detailed example with added CSS and a link to her ambient light demo on CodePen.

Status

At the time of writing support is only available in Firefox and Chrome beta for Android but here's a short video of her code in action:


Of course, these are not the only web technologies that are part of responsive web design but if you want to show the world that you know more than just media queries, they're a good place to start.

Song: On The Web ♪

The other day Joe Leech tweeted that he’s “thinking about writing a sit-com about web designers. Best friends Mark Down and Rich Snippets and their hilarious adventures.” Well a sitcom needs a cheesy theme tune so here’s my crack at writing a short song for it. Now all we need are a script, location, actors, production staff…

Go to the song’s SoundCloud page to download, leave a comment, etc.

Lyrics

Monday morning, climb the stairs and reach my desk.
Inbox going crazy with so many change requests.

Just another day at our web design agency
Without the clients this would surely be
The perfect industry

We spend hours in front of a screen
Fuelled by sandwiches and caffeine
But it's worth it 'cause across the globe, our work will soon be seen
On the web

There's a new frontier
On the web
Nice bunch of people here
On the web
You can join us too
On the web
Yeah, it must be true
It's on the web, on the web, on the web.
On the web.

Credits

The globe icon in the cover image is from the wonderful iconmonstr.com.

On Responsive Images — An interview with Dr. Stanley Dards

Wanting to serve different size images to different size screens is nothing new but at last the web has a practical solution for responsive images and art direction. Thanks to a lot of hard work by a lot of people, the Responsive Images Community Group has achieved the goal of seeing its API becoming a valuable building block of the web.

The <picture> element and its related srcset and other attributes are already being incorporated in Blink, Gecko and WebKit, have been included in the HTML5 validator and are part of the WHATWG HTML5 spec. A triumph of common sense and cooperation — hurrah!

To celebrate this, I was lucky enough to interview Dr. Stanley Dards, the wise old man of the web, to get his unique insight on the topic.

And here’s a good practical summary of responsive images and how you can use them today.

Web API Design – a definitive guide

Cover of Web API Design book“Web API” is a confusing term. It can refer to interfaces to be implemented by web software such as browsers, for example the W3C geolocation API, etc. It can also refer to how a web service exposes its data, and it’s in this context that Brian Mulloy has written what I hope will become the bible of REST-based API design. His ebook, entitled Web API Design, is available for free (well, in return for your email address).

As web developers, we want APIs that are easily-understandable and consistent, resulting in less time reading documentation and more time experimenting and being pleasantly surprised that something just works.

At around 30 pages long it’s a quick read but gets straight to the point with concrete advice. Right from the start he emphasises a pragmatic rather than theoretically ideal approach — developers should be able to experiment with and learn the API without the documentation — and highlights good and bad examples from popular APIs. Here’s a quick summary of some of his recommendations.

  • Use two base URLs per resource, e.g. /dogs and /dogs/1234
  • Keep verbs out of your base URLs, unless the data is the result of an action, e.g. “calculate” or “translate”.
  • Use HTTP verbs (GET, POST, PUT, DELETE) to operate on the data.
  • For clients that don’t support this, make the method an optional parameter, e.g. /dogs/1234?method=delete
  • Use plural rather than singular nouns.
  • Use concrete rather than abstract names.
  • Put complexities after a question mark, e.g. /dogs?color=red&state=running
  • Be verbose but simple in your error messages, ideally linking to online docs.
  • For specific fields, us a comma-delimted list, e.g. /dogs?fields=name,color,location
  • Use “limit” and “offset” for pagination, e.g. /dogs?limit=25&offset=50
  • To specify formats, use the familiar dot notation, e.g. /dogs/1234.json
  • Use JSON as the default format, following JavaScript conventions for attribute names.
  • Use OAuth 2.0 for authentication.

There seems to be a relative lack of guidance in this field so this book has a good shot at becoming the go-to reference. The result of that would be more consistency between APIs and an easier life for website and app creators. Of course, differences in existing APIs will linger on because of the difficulty in upgrading them once released, but that’s one more reason why it’s important to base an API design on solid guidelines such as these in the first place.

Download the ebook here: offers.apigee.com/web-api-design-ebook/ (no affiliation)

Also, here are a couple of other good resources about designing RESTful APIs:

Free HTML5 template

Official HTML5 logoAfter being asked for a bit of advice by a colleague, I decided to make a very simple starter template for creating an HTML5 page. You can download it here:

Download HTML5 template

Notes

The tricky part is making sure it works in older browsers, for which I used the following two steps:

1. Normalize.css
(Click on “normalize.css” -> “Raw” to get the main CSS file.)

This makes all browsers behave the same way, including making relevant HTML5 elements into block elements. I recommend minifying the CSS to save bandwidth and time.

2. HTML5 Shim

This makes HTML5 elements styleable in old versions of Internet Explorer. Put it after all styles in <head>.

I’ve also added a viewport meta tag as follows which, in most cases, should improve the readability of the page on small screen devices.

<meta name="viewport" content="width=device-width, user-scalable=yes">

Going further

You might want to include Modernizr in your page, to enable you to detect support for newer CSS3 and JavaScript features.

For a much more full-featured template, there’s the popular HTML5 Boilerplate with a host of built-in goodies.

I’d love to hear if this is useful for you or if you have ideas for improvement – let me know in the comments below.

On vendor prefixes — An interview with Dr. Stanley Dards

At last, the existence of vendor prefixes, one of my pet peeves, is under the spotlight. Also at last, the fact that not all modern browsers are WebKit (shock!) is getting some attention.

I (personally) believe vendor prefixes cause more harm than the problem they were designed to solve, namely how to elegantly introduce experimental features in browsers. My belief is that a non-browser-specific prefix such as -beta- has fewer obstacles to overcome than other proposals. Having said that, there’s clearly no easy, one-size-fits-all answer but hopefully more awareness and public discussion will lead to a more plausible solution.

So far, there have been great contributions to the discussion from all sides. A selection of ones I’ve found valuable, but may not necessarily agree with, are listed here:

And as if that wasn’t enough, here are the insights of one Dr. Stanley Dards:

List of JavaScript charting libraries

Illustration of some chart styles.I’m looking to make some pretty JavaScript charts and was wondering which library to use. I’ve used Flotr in an Opera extension and played around with gRaphaël in the past, but I want to do a more thorough comparison. First step is to list all the charting libraries I can find, so here it is…

Open source

Minimal or no dependencies

Require general-purpose library (e.g. jQuery)

Not open source

A few links for reference

Some are a little out-of-date but they’re still useful.

Web conference blues

You know that lonely feeling, where all the hip web designers and developers gather at the coolest conference and you’re stuck at your desk? Here’s a song for those of us that miss out on all the glamour.

The original song, by the way, is Folsom Prison Blues by Johnny Cash.

Video URL (with captions): www.youtube.com/watch?v=u_gAPRJmEWs

Downloads

For your downloading pleasure, here are the video and audio–only files.

License is Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported. If you need a media player, I recommend VLC.

Lyrics

I see the tweets a-comin’
They’re comin’ down the screen.
They’ve all got the same hashtag and I,
I know what that means.
It means I’m stuck here at my desk
and time keeps draggin’ on.
And the web conference keeps rollin’
all tickets sold except one.

When I was just a baby
my momma told me “Hey!”
“Always do things early or
you’ll regret it some day.”
Well I knew I should have booked
but I left it too late.
Yes, I missed the earlybird discount.
Why did I procrastinate?

I bet there’s web folks tweetin’
in a fancy conference hall.
They’re probably drinkin’ coffee
and talkin’ ’bout HTML.
Well I knew I had it comin’.
I know it’s not to be.
But those tweets, they keep on comin’
and that’s what tortures me.

If my boss gave me approval,
let me register online,
I’d jump on to the next plane.
I could still make it on time.
But I’m stuck here at my desk.
Here’s where I’m gonna stay.
I’ll just go right back to Farmville
and hoe my blues away.