Working with HTML5 data attributes

Before HTML5, working with arbitrary data sucked. To keep things valid, you had to stuff things into rel or class attributes. Some developers even created their own custom attributes. Boy, was it a mess.

But that all changed with the introduction of HTML5 custom data attributes. Now you can store arbitrary data in an easy, standards-compliant way.

How do data attributes work?

A data attribute is exactly that: a custom attribute that stores data. They are always prefixed with data- followed by something descriptive (according to he spec, only lower case letters and hyphens are allowed). An element can have any number of data attributes you want.

Here’s an example using a list item to store data for a user:

Of course, this data isn’t very useful to a visitor because they can’t actually see it, but it’s wildly useful for building web applications. Imagine a delete button in your app:

All the data you need is right there to send to your backend script. No morerel stuffing or parsing IDs and actions out of other attributes. Data URLs make your life easier.

What can you store?

One thing to remember when working with data attributes is that you can’t store objects in them. Well, you can if you serialize them, but we’ll save that for another post.

For now, just know that you’re pretty much limited to storing strings.

Reading/writing data attributes with JavaScript

Using the delete button as an example, let’s look at how we can access this data with JavaScript.

Pretty simple, right? Now you can pass cmd and id to your app in an AJAX request or do whatever else you need to do with it.

Reading/writing data attributes with jQuery

Here’s the same thing using jQuery’s .attr() method:

Don’t get this confused with jQuery’s .data() method. Although there is some overlap in how data attributes and .data() work, they’re two totally different things. If you’re not familiar with it, just stick with .attr().

Using the dataset API

HTML5 actually has an API just for working with this type of data. Alas, IE10 and below don’t fully support it, but it’s still worth mentioning.

Using the button example again, here’s how to get and set data attributes using the dataset API:

Note how there’s no data– prefix or dashes here. Similar to the way CSS properties work in JavaScript, you’ll need to use camel case notation. The dataset API converts each one so you’ll always have data-some-attribute-name in your HTML and dataset.someAttributeName in your JavaScript. Magic!

Things you can do with data attributes

The examples above are very basic, but you can do so much with custom data attributes. Here are a few examples off the top of my head.

Filtering

Say you have a list of things and you want to filter them by keyword. Just put the keywords into a data attribute and write a short script to loop through and show/hide them accordingly.

Here’s a quick and dirty filter using jQuery:

Styling

It’s arguably better to use classes, but you can style things against data attributes too. Here’s how to apply a style if the element has a certain data attribute (regardless of its value). First, the HTML:

Now the CSS:

But what if we wanted to style it based on the data attribute’s value? This will work for any data-warning attribute that contains the word error:

Configuring

Bootstrap uses data attributes as an HTML alternative to configuring plugins via JavaScript. Here’s an example of a popover:

A better way to store data

Custom data attributes are widely used all over the web. The nice thing is that they work fine in older browsers, and they adhere to web standards moving forward. That means you can start using them today knowing that they won’t stop working tomorrow.

I’ve shown you a few common ways to use custom data attributes. What other uses can you think of? Have you used them before? Let me know by commenting below!

What is React? The good, the bad, the ugly.

What is React?

How does React compare to Angular, Ember, Backbone, et al? How do you handle data? How do you contact the server? What the heck is JSX? What is a “component”?

Stop.

Stop it right now.

React is ONLY THE VIEW LAYER.

React is often mentioned in the same breath as other Javascript frameworks, but “React vs Angular” doesn’t make sense because they aren’t directly comparable things. Angular is a complete framework (including a view layer), React is not. This is why React is so confusing to understand, it’s emerging in an ecosystem of complete frameworks, but it’s just the view.

React gives you a template language and some function hooks to essentially render HTML. That’s all React outputs, HTML. Your bundles of HTML / Javascript, called “components”, are allowed things like storing their own internal state in memory (such as which tab is selected in a tab view), but in the end, you just barf out HTML.

You absolutely cannot build a fully functional dynamic application with React alone. We’ll learn more about why below.

The Good

After working with React for a while, I’ve seen three very important benefits surface.

1. You can always tell how your component will render by looking at one source file.

This may be the most important benefit, even though it is not different from Angular templates. Let’s use a real-world implementation example.

Say you have to update your site’s header with the user’s name upon login. If you’re not using a Javascript MVC framework, you might do this:

I can tell you from experience that this code will ruin your life and your friends’ lives. How do you debug the output? Who updated the header? Who else has access to the header HTML? Who holds the source of truth for the name being visible? This DOM manipulation is just as bad as a GOTO statement for reasoning about your program.

Here’s how you might do it in React:

We can tell instantly how this component will render. If you know the state, you know the rendered output. You don’t have to trace program flow. When working on complex applications, especially in teams, this is critically important.

2. Bundling Javascript and HTML into JSX makes components easily understandable.

The weird mix of HTML / Javascript soup above might make you cringe. We’ve been conditioned to not put raw Javascript in the DOM (like onClick handlers) since we were wee developers. You’ll have to trust me, though; working with JSX components is really nice.

Traditionally you separate views (HTML) from functionality (Javascript). This leads to monolithic Javascript files containing all functionality for one “page”, and you have to trace complex flow from JS > HTML > JS > bad-news-sad-time.

Tying functionality directly to markup and packaging it in a portable, self-contained “component” will make you happier and less filthy in general. Your Javascript has intimate knowledge of your HTML, so mashing them together makes sense.

3. You can render React on the server.

If you’re building a public facing site or app and you’re following the render-it-all-on-the-client path, you’ve already done it wrong. Client-only rendering is why Soundcloud feels so slow and why Stack Overflow (purely server-side rendering) feels so fast. You can render React on the server, and you should.

Angular and others encourage you to do disgusting things like render your page with PhantomJS and serve that to search engine crawlers based on user agent, or pay actual cash money for that as a service. Ugh.

The Bad

Don’t forget that React is only the view.

1. You DO NOT GET any of the following:

  • An event system (other than vanilla DOM events)
  • Any AJAX capabilities whatsoever
  • Any form of a data layer
  • Promises
  • Any application framework at all
  • Any idea how to implement the above

React on its own is useless for the real world. Worse yet, as we’ll see, this leads to everyone reinventing the wheel.

2. The documentation is not “accessible” nor “good.” Again, this is a blog post for stupid people. Look at the first part of the sidebar on the documentation page:

React documentation sidebar

There are three separate, competing quickstart guides. I’m overwhelmed and I’m not even drunk. The sidebar below that is straight out of my nightmares, with sections that obviously shouldn’t be there, like “More About Refs” and “PureRenderMixin”.

3. React is large for how little you get, including how little cross browser support.

 

That’s without the react-with-addons library you will need to actually develop a real app!

That’s without the ES5 Shim library you need to support IE8!

That’s without any sort of application library of any kind!

React is a comparable size with Angular, even though Angular is a complete application framework. React is frankly bloated for how little functionality you get. Hopefully, this will improve in the future.

Stop Saying Flux

Perhaps the most annoying part of React development is “Flux.” It’s far more confusing than React. The name “Flux” is a pretentious barrier to understanding.

There is no such thing as Flux. Flux is a concept, not a library. Well, there is a library, sort of:

“Flux is more of a pattern than a framework”

Ugh. The worst part is the name: React didn’t reinvent the last 40 years of UI architecture knowledge and come up with some brand new concept for data management.

The concept “Flux” is simply that your view triggers an event (say, after the user types a name in a text field), that event updates a model, then the model triggers an event, and the view responds to that model’s event by re-rendering with the latest data. That’s it.

This one-way data flow / decoupled observer pattern is designed to guarantee that your source of truth always stays in your stores / models. It’s a Good Thing™.

The bad side of Flux is that everyone is re-inventing it. Since there’s no agreed on event library, model layer, AJAX layer, or anything, there are many differentFlux” implementations, and they all compete with each other.

Should I Use React?

Short answer: yes.

Long answer: unfortunately, yes, for most things.

Here’s why you should use React:

  • Works great for teams, strongly enforcing UI and workflow patterns
  • UI code is readable and maintainable
  • Componentized UI is the future of web development, and you need to start doing it now.

Here’s why you should think twice before you switch:

  • React will slow you down tremendously at the start. Understanding how props, state, and component communication works are not straightforward, and the docs are a maze of information. This will be countered, in theory, by a grand speed up when your whole team is on board.
  • React does not support any browser below IE8, and never will
  • If your application / website doesn’t have very much dynamic page updating, you will be implementing a lot of code for a very small benefit.
  • You will reinvent a lot of wheels. React is young, and because there’s no canonical way to do events / component communication, you’ll have to build large component libraries from scratch. Does your application have dropdowns, resizable windows, or lightboxes? You’ll probably have to write those all from scratch.

Convert an image to a data URI with your browser

You probably know that you can use data URIs in just about any browser now, but how do you convert an image to a data URI? It turns out, most browsers can do it for you.

What is a data URI?

Data URIs are all the rage these days. They let you reduce HTTP requests by putting small images right in your HTML or CSS. For a full overview of what they are and how to use them, check out this post on CSS Tricks.

Here’s what they look like in case you need a refresher:

Now I’m going to show you how to generate these URLs using a tool that every web developer has: your browser.

Chrome & Opera

This trick works in Chrome and newer versions of Opera, since they use the same rendering engine.

1. Load the page that contains your image (loading the image directly won’t work) and right-click on it. Select Inspect Element.

2. You’ll see the console appear. Now click on the value of the src attribute.

3. The console will switch to the Resources tab and highlight the image. Right click on it and select Copy Image As Data URL.

4. Now just paste it into your HTML or CSS!

Firefox

Firefox is the easiest because it works for images on a webpage as well as images loaded directly in the browser. There’s also one less step compared to Chrome/Opera.

1. Load the image or the page containing your image and right click on it. Select Inspect Element.

2. The image will appear highlighted in the DOM. Right click on it and select Copy Image Data-URL.

3. Paste it into your HTML or CSS.

Safari

Safari is similar to Chrome, but the UI is a bit different. It’s the same number of steps, and it won’t work if you load the image directly in the browser—it has to be on a page.

1. Load the page that contains your image and right-click on it. Select Inspect Element.

2. The console will appear with the image highlighted. Click on the value of its src attribute.

3. The image will be shown in the console. Right click on it and select Copy Image.

4. Paste it into your HTML or CSS.

Internet Explorer

Alas, I haven’t found a way to copy an image as a data URI using IE9, 10, or 11, but you can use a free online tool instead.

A free online tool

Another easy way to generate data URIs is to use a free service. DataURL.net lets you drag and drop an image and gives you the resulting code instantly. So if you don’t like the in-browser method (or if your browser doesn’t support it) you’re not out of luck.