The HTML5 DOM Element API: classList

The classList object is a set of functions that helps you manipulate the class attribute on a node. It provides functionality that allows you to add a class to the node, remove a class, find out if a node contains a class, and lets you toggle a class. It is a pretty simple API to interact with so let us run through an example that uses the available functions.

Starting HTML:

And now for the JavaScript:

This is something that JavaScript libraries have been helping us with for awhile and it is great to see it make its entrance as a native API. Unfortunately, support is still lagging a bit. You will find it available in Firefox and Chrome; the rest of the browsers only have it in more recent versions and IE does not have support for it at all, at the time of this post. Here is the full caniuse page.

3 Day Startup from a Mentor's Perspective

What is 3 day startup? From the 3DS website:

The idea of 3 Day Startup is simple: start tech companies over the course of three days. We rent work space for an entire weekend, recruit 40 student participants with a wide range of backgrounds, cater food and drinks, and bring in top-notch entrepreneurs and investors. The participants pick the best ideas for startups during the Friday brainstorming session and deliver prototypes and investor pitches on Sunday night.

I helped mentor the October 21-23, 2011 3 day startup in Austin and in addition to having a lot of fun myself, I came away with some insights of what made teams successful and ideas for what could have gone better.

The initial idea

The best initial pitches were those that had a small focus and scope. A great way to know if you have a clear idea is if you can explain it and have others understand it in a 10-20 second summary. In that summary you want to describe the problem, the solution, and how it will make money.

A small focus and scope does not end at the end of brainstorming. Even if your idea changes from what it was during the initial brainstorming, keeping the new scope small really helps ensure that you have enough time to do research and prepare answers to the common questions at the final pitch.

Learn the basics of software engineering

Before the event, have experience with a version control system like subversion or git. While dropbox is good for sharing files, you will find it is much easier to work on a team project with real version control. It also would not hurt to read up on best practices for web development and familiarize yourself with mobile application, web or native, development.

Build a project with Django or Ruby on Rails

While you will not be building the final production quality product in three days, having a functional prototype is an impressive addition to the final pitch and gives you the opportunity to test it out on real customers during the weekend. Why Django or Ruby on Rails? Both have plugins and publicly available applications that make it very easy to get the generic parts out of the way quickly such as user management, administration panels, and debugging tools. I also recommend learning how to deploy an application to a production environment, your own server or a service such as Heroku, EC2, or the Google App Engine.

If you already know another framework that you are comfortable with, go with it. Django and Ruby on Rails are merely suggestions if you are starting from scratch.

To be even more prepared, setup a subversion repository on your computer or a server you own and setup a bare bones project ahead of time. When you form your team, you can immediately start iterating on the product.

The final pitch

If using a technical demo, have a backup plan as part of your slides. If the tech demo fails, you can quickly fall back to a walk through.

You will want your pitch to answer these common questions:

  • What is the problem you are trying to solve?
  • What is it that your product provides that differentiates you from the competition.
  • How are you going to make money?
  • How are you going to acquire customers or users?

When responding to questions about your pitch, keep the answers short and on point, you don’t want to ramble. If you do not have an answer to a question, say so and take it as something you need to research. You only have three days, you cannot know everything about your product.

Closing

Most importantly, have fun and meet people! 3DS brings together 40+ people who enjoy building products. So much so that they have given up their weekend to do it, just like you have. Even if your product does not make it out of the weekend, you now have some friends you can call for any future endeavors.

To find out if there is a 3 day startup at your university or for more information about 3 day startup, visit the 3ds website.

The HTML5 DOM Element API: Dataset

Datasets are one of the new Element features added with the HTML5 spec. They allow you to add arbitrary attributes to DOM Elements that can be easily accessed and modified via JavaScript. These attributes are great for adding additional information for projects such as photo galleries that can use the attributes to enhance the display.

Using data attributes on elements

Datasets are added to an element via element attributes. A dataset attribute is prefixed by data- and followed by the name. For example, data-author.

For this post, we are going to use a photo gallery as an example of when you might want to use datasets to add additional markup to your HTML. To start, let us create the first div with attributes that define the author, location, and date of the photo. Here is the markup:

As you can see, the three items we want in the dataset are prefixed by data- and are assigned a value the same way as any other HTML attribute.

Accessing an element’s dataset

To access the dataset of an element, simply use the attribute dataset. Here is a quick example.

The dataset attribute returns a DOMStringMap, a new datatype added for datasets. Note: hyphenated attribute names are turned into camel case for JavaScript access.

Modifying and removing an element’s dataset

Modifying an item in the dataset is very easy, just assign the property in the dataset a new value.

Deleting is equally easy, just use the keyword delete and specify the property of the dataset to delete.

Using data attributes with CSS

Like other HTML Element attributes, dataset attributes can be used as part of CSS selectors. Adding a blue background to all divs with Dave as the author looks like the following:

Datasets provide an easy way to associate little bits of meta data with your HTML tags and allows easy access from your JavaScript. For more intensive JavaScript applications you will still be better off using JavaScript objects to hold your state. However, for quick projects like a photo gallery, dataset attributes provide easy access to additional data for each element. As far as browser support, here is the caniuse page.

Introduction to Google Guava's Joiner class

The Joiner class performs the complementary function of the Splitter class. The Joiner class will join an Iterable, an array, or a variable argument list using a given separator in between them.

Starting with the basics

The basic usage of the Joiner uses the on function and then by calling join with an array or Iterator object. To demonstrate this, let us use a Set of names to create a comma separated list.

Dealing with nulls

Like the Splitter, the Joiner comes with a couple of utilities for dealing with null in the input. The first is the skipNulls function that will return a Joiner which will automatically skip over any nulls it encounters when iterating over the elements. The second is the useForNull function which will use the parameter it was given in place of nulls. Here are examples of using each one:

If you use both the skipNulls and useForNull on the same joiner, it will throw an UnsupportedOperationException.

Using the Joiner class to build up a StringBuilder

In addition to joining a String all at the same time, you can build it up instead using a StringBuilder. The appendTo function of the Joiner takes the same arguments as the join function: an Iterable, array, or argument list an will work for both StringBuilders and any Appendable object. One caveat of this function is that it will only add the separator between elements within each function call. Below is an example of using it with a StringBuilder.

As you can see, the commas were only added in between elements in the same appendTo call which is why johndanmatt was not separated.

Using the MapJoiner (new in Guava 10.0)

A good example of using a MapJoiner is to create a query string out of a Map of query parameters. Let us use the following map:

{"param": "v", "p2": "v2", "q": "java"}

And the code:

The MapJoiner does not have utilities for trimming and cleaning up the strings, so that will have to be done while building the Map. You can read the full documentation on the Joiner class here.

View the previous post on Google Guava’s Splitter class

Introduction to Google Guava's Splitter class

The Splitter class takes a common, and what should not have to be verbose, exercise and makes it easy and readable. Let us start with a scenario, you have a list of key value pairs that you need to parse into a map. We are also going to assume the input could be malformed with empty entries and extra spaces. For the sake of this example, let us use names and user ids.

"dave:123, john:314,, matt:989"

Now, how this is typically handled:

This ends up being rather verbose and also error prone. We will see how the Splitter class makes this much easier and readable.

Starting with the basics

The simplest example of the Splitter is parsing a standard comma separated list.

Pretty straightforward. In addition to a string separator, the Splitter.on function can also use a char, CharSequence, or a Pattern. The API provides a convenience method Splitter.onPattern that will turn a String into a java Pattern.

Utilities to sanitize the input

We saw in the initial scenario a poorly formatted string that required us to check for null and trim at various points to clean up the input. The Splitter class comes with the utility functions omitEmptyStrings and trimResults to take away some of that boilerplate code.

Another benefit of using the utility functions to clean up the split string is readability. When someone is reading your code, it is much easier to understand what is happening when seeing omitEmptyStrings and trimResults versus checks for null, checks for empty string, and various trim calls.

Using the MapSplitter (new in Guava 10.0)

The MapSplitter allows you to take a list of key value pairs and easily turn it into a Java Map. Well, that sounds great for solving our initial scenario, let us see it in action.

That looks much better. We removed the loop, the input was sanitized, we threw out any empty strings, and we broke up the separated values into key/value pairs. It also reads a lot better:

Split a string on comma, omit empty strings, trim those results, then use colon as a key value separator. With these rules, split stringToSplit

This is much easier to read than our initial version. You can read the full documentation on the Splitter class here.

JavaScript Error Logging

A useful technique that I have been using to help keep track of JavaScript errors has been to use the OnError event to help log client side errors that slip through the testing process. In addition to the properties that come with the JavaScript exception (the error message, the url of the script, and the line number) I log the url of the page that they were on when the problem occurred which makes reproducing the situation much easier. Another nice little benefit of catching errors through my own callback is being able to suppress the error message from the user, in some browsers this can be as invasive as a popup (IE). On to some code.

The code should be fairly straightforward. The OnError event is assigned my own error handler. Whenever a JavaScript error occurs a request is sent to /rpc/client-error-log with the details of the problem. The return true at the end of errorHandler suppresses the error message from the user. On the server side, I log the error that occurred. Every morning I send myself an email with all the error messages for the past 24 hours. A fair number of them are problems that I cannot, or have not, figured out how to fix such as “Error loading script”. Although when I occasionally introduce a bug into the wild, this gives me all the information I need to reproduce and fix it (usually).