Category Archives: Tutorial

Auto-focusing HTML form-fields with smart labels

A thing that I have strived for as long as I can remember is simplicity and ease of use in the work that I do. When working with HTML forms a key manifestation of this philosophy is something as simple as being able to click a label and have focus to be set to the corresponding form-field, i.e. input; textarea; or select element. When I first started doing this, my approach was to use the for attribute of the label element, so that its value matched the id of the form-field, e.g.:

<label for="inputId">Label</label>
<input id="inputId" type="" />

While the above model works from a usability standpoint it fails (in my opinion) from a maintainability standpoint, as you need to either manually or programmatically ensure that the for attribute in the label element matches the id attribute of the corresponding form-field.

… but there’s a better way: If you nest the form-field inside of the label, clicking any part of the element or its descendants will set focus to the form-field without requiring any additional attributes whatsoever. The structure for this is:

<label>Label </label>

… e.g.:

<label>Input <input type="" /></label>

<label>Textarea <textarea></textarea></label>

<label>Select<select></select></label>

From here on it’s really up to you to structure your form-control (i.e. combination of label and form-field) in any way you want. My current model is inspired by the naming conventions of the BEM (Block, Element, Modifier) methodology and looks like, e.g.:

<label class="formcontrol">
    <b class="formcontrol-label">Label</b>
    <input class="formcontrol-input" type="text" />
</label>

Note #1: I don’t use elements for styling (anymore), so the <b> element is really just an inline-element which takes up less characters than, e.g. a <span>.

How to make RESTful APIs flexible and sensible to work with

I have been an advocate for RESTful APIs since I first came across the concept in 2010, and although it took me a while to wrap my head around the concept, I knew from the first moment that this was something that made sense to me compared to the SOAP based APIs that I had previously been working with. Though initially starting out with RESTful APIs in their purest form (so to speak), I have discovered a couple tricks which make them a lot easier to work with, and in this post I’ll share these with you.

Fundamentals of RESTful APIs

First of all, let’s make sure that we have the same basic understanding of the concept of a RESTful API. It’s an API which uses:

  • A base URI, e.g. https://path.to.api.
  • Standard HTTP methods, i.e. POST; GET; PUT; PATCH; and DELETE to request and manipulate data.
  • URLs which make it (potentially) easy for a human to interpret which information is being requested, e.g. GET https://path.to.api/v1/users/1, i.e. get information about the user with ID 1.
  • Standard HTTP status codes as high-level responses to requests, e.g. 200 OK; 201 Created; 401 Unauthorized; 403 Forbidden etc. which makes the overall status of a request easy to interpret.
  • An internet media type for data, e.g. JSON.
  • Autonomous requests from a client (API consumer) which contain all of the information required for the API to process the request, i.e. the API doesn’t need to retain the state of the client.

The common denominator here is: Standards, i.e. a RESTful API is built using already existing standards, rather than having to invent public classes which are specific to a said project.

Response Types

With a RESTful API you have the following types of responses:

  1. Resource: A resource is an extensive object containing all information regarding the resource, e.g. GET https://path.to.api/v1/users/1 should result in a response containing all available information about the user with ID 1.
  2. Collection: A collection is a list of a specific kind of resource, e.g. GET https://path.to.api/v1/users should result in a response containing a list references to all available user resources.

Basically, what this means is that is that if you wanted information about all of the users (just to stay with the example) in the system you would:

GET https://path.to.api/v1/users

… to get the entire collection of users, and then for each resource in the collection:

GET https://path.to.api/v1/users/1
GET https://path.to.api/v1/users/2
GET https://path.to.api/v1/users/3
GET ...

… to get the information regarding each resource.

Improvements

As REST is a conceptual approach to building an API each development team has to take it from here and build something which suits their needs. In the remainder of this post, I will be examining various approaches which I have found useful.

Basic Versioning

As you may have noticed the examples above all contain v1 as part of the request URL, i.e. an abbreviation for “version 1”. The reason behind including this is simply to avoid breaking functionality in the case that your team decides to build a new API from scratch, e.g.:

At some point you should probably get rid of the v1 API for maintainability reasons, but by using versioning you can build the new version alongside the old without constantly having to stress over having to make sure that the consumers of the API, e.g. external users, are in sync with your progress.

Flexible Collections

Instead of merely having collections being a list of resources, I suggest structuring the response into an object, which includes meta-data about the collection and where most of the meta-data properties can be given values as part of a request thus making the collection more flexible to work with, i.e. (numbered for convenience):

  1. Items: An array of resource objects.
  2. Sort: The property name in the individual resource objects by which the whole collection of data is sorted, e.g. {sort: 'name'} or {sort: 'id'}, both before being sent as a response from the API and as sorted in the items array.
  3. Reverse: A property that lets you reverse the direction by which the whole collection of data is ordered, i.e. {reverse: true}, before being sent as a response from the API. In my opinion, the default should be ascending, and thus applying the true value to the property should return the collection in descending order.
  4. Limit: The maximum number of resource object in the items array, in case you only wish to include a subset of the whole collection as part of the items array, e.g. {limit: 25} will include a maximum of 25 resource objects regardless of the length of the whole collection.
  5. Offset: The offset in the whole collection of data from which the limit is calculated. When used together with limit, it makes it possible to incorporate paging of the response data.
  6. Previous: A link to the previous element in the collection (if applicable).
  7. Next: A link to the next element in the collection (if applicable)
  8. Total: The total number of resource objects for the request regardless of how many are included in the items array, so that you always know the size of the total data-set.
  9. Details: The detail level of each resource object in the items array, e.g. specified by a string, for instance all. A common approach in REST is to have each resource in a collection contain a minimum of data, e.g. a URL to where the complete set of data for the resource can be acquired, but I have found that sometimes it makes more sense to get all information regarding the resources as part of the collection instead of as multiple subsequent requests.

The following request:

GET https://path.to.api/v1/users?sort=name&reverse=true&limit=10&offset=50&details=all

… should thus result in the following response (please note that the individual resources in the items array have been left out):

{
    items: [],
    sort: 'name',
    reverse: true,
    limit: 10,
    offset: 50,
    previous: '/v1/path.to.previous',
    next: '/v1/path.to.next',
    total: 200,
    details: 'all'
}

There you have it: RESTful flexible collections.

Examples

Get all users sorted by name:

GET https://path.to.api/v1/users?sort=name

Get all users sorted by name in reverse order:

GET https://path.to.api/v1/users?sort=name&reverse=true

Get the 25 first users:

GET https://path.to.api/v1/users?limit=25

Get all users except the first 25:

GET https://path.to.api/v1/users?offset=25

Get users 25-49:

GET https://path.to.api/v1/users?limit=25&offset=25

Get the total number of users without any additional information for each resource:

GET https://path.to.api/v1/users?limit=0

Using LESS to DRY out your BEM-style CSS and increase maintainability

If writing scalable CSS for your HTML5 projects is of concern to you, chances are that at some point you’ve bumped into the Block, Element, Modifier (or BEM for short) approach. Basically (in my interpretation) what BEM advocates is a model for writing/organizing CSS where:

  • Anything that needs to be styled has a class name, i.e. no styling based on element types.
  • Classes are independent and defined on the same level, so that no styles are dependent of their ancestry, i.e. no class nesting.
  • Related classes are grouped together using a common block name.

The basic CSS for a BEM model is showcased below:

.block {}
.block-element {}
.block--modifier {}

Explanation:

  • The block represents the main component.
  • The block-element (one hyphen) represents a part (sub-element) of the component.
  • The block--modifier (two hyphens) is a modification to the block, e.g. a different background color, layout etc.

(Note: The source BEM approach referenced in the introduction uses “_” (underscores) as separators, but I use “-” (hyphens/dashes) – it’s just a matter of personal preference.)

An HTML structure for the block could look something like this:

<div class="block">
    <div class="block-element"></div>
</div>

<div class="block block--modifier">
    <div class="block-element"></div>
</div>

The example shows two versions of the .block component which both contain a sub-element .block-element, but the second component also contains a .block--modifier which could e.g. display it with a different background color. As all CSS classes start with the same block name it’s easy to see that they are part of the same block.

Now, even though this makes for some pretty understandable and scalable CSS (as blocks and sub-elements will look the same regardless of their context), from a maintainability standpoint, there is a lot of repetition as each style declaration starts with the block name, i.e. the code is not especially DRY, and e.g. changing your mind about the block name will require you to update multiple lines of CSS (3 in the basic example above).

(LESS) CSS pre-processing to the rescue

Luckily, if you’re using the LESS CSS pre-processor (and I’m sure that SASS has the equivalent functionality) there’s an easy way for you to organize your source code which will DRY it out and make it a lot more maintainable: LESS gives us the ability to reference the current selector parent using the “&” (ampersand) character. This means that by using LESS we can reduce our LESS/CSS code to this:

.block {
    &-element {}
    &--modifier {}
}

Explanation: For the -element and --modifier declarations the “&” (current parent selector) will reference the .block name, thus rendering them as .block-element and .block--modifier respectively.

Implementing the above approach means that when you want to change the block name, to e.g. myblock, you only need to change the initial block name (i.e. the first line) and LESS will take care of the rest, i.e.:

.myblock {
    &-element {}
    &--modifier {}
}

…which renders into:

.myblock {}
.myblock-element {}
.myblock--modifier {}

There you go: Scalable, DRY and low-maintenance BEM-style CSS!


Notes

Multi-level sub-elements

Many times your blocks will probably contain multiple levels of nested sub-elements, but you should still keep all of the classes directly related to the main block to ensure that the individual sub-elements parts are as loosely coupled as possible, e.g.:

HTML

<div class="block">
    <div class="block-element">
        <div class="block-element2">
            <div class="block-element3"></div>
        </div>
    </div>

    <div class="block-element4"></div>
</div>

LESS

.block {
    &-element {}
    &-element2 {}
    &-element3 {}
    &-element4 {}
}

Further DRY’ing your LESS

If you’re really (as in really, really) DRY, you will have noticed that there are redundant hyphens/dashes all over the examples, so to get rid of these you can insert additional level in the LESS, i.e.:

.block {
    &- {
        &element {}
        &-modifier {}
    }
}

or even:

.block {
    &- {
        &element {}

        &- {
            &modifier {}
        }
    }
}

… but maybe that is unnecessarily obsessive compulsive.

How to upgrade to Windows 10 under Parallels Desktop 10 for Mac

This article is for those of you who (like myself) are running Microsoft Windows as a virtual machine under Parallels Desktop 10 for Apple Mac OS and have experienced problems while attempting to upgrade to Windows 10 (from Windows 8.1 Pro in my case).

A couple of days ago Microsoft released Windows 10 and although the integrated update tool in Windows 8.1 Pro told me that “Windows 10 will not run on this PC” due to the Parallels display adapter (WDDM), I had been running a technical preview of Windows 10 in another virtual machine, so I was certain that my machine (Apple 13″ retina MacBook Pro, late 2013) would in fact be able to run it. I found a support page from Parallels which detailed a solution and felt ready to go. What followed was a frustrating mix of recurring (yes, I tried multiple times) “setup has failed to initialize the working directory” and “something happened” errors. Eventually, after realizing that doing the same thing over and over again probably wouldn’t change the outcome, I decided on a different approach which turned out to work flawlessly:

  1. Download the appropriate Windows 10 ISO file to Mac OS from https://www.microsoft.com/en-us/software-download/windows10ISO:
    1. Select the appropriate edition and click “confirm”. You’ll have multiple versions to choose from. Refer to this page for more info.
    2. Select the product language and click “confirm”.
    3. Download the Windows 10 ISO in either a 32-bit or 64-bit version.
  2. In Parallels 10 on Mac OS:
    1. Open the “(Parallels Desktop) Control Center” to view your virtual machines.
    2. Edit the virtual machine, that you wish to upgrade to Windows 10, by clicking the gear symbol/icon.
    3. Go to the “hardware” tab.
    4. Click “CD/DVD”.
    5. In the “connect to” select “choose an image file”.
    6. Locate the Windows 10 ISO file.
    7. Click “open.
    8. Start the virtual machine.
  3. In the virtual machine:
    1. Open Windows Explorer (hotkeys: cmd e).
    2. Click on the (“This PC” >) “DVD drive” to access the contents of the Windows 10 ISO file.
    3. In the list of folders/files on the ISO, double click the “setup” application.
    4. Complete the setup process and you will be running Windows 10.

That’s it. I hope it helps someone out there.