Table of contents
It’s based around how CSS documents came into play, the concept behind CSS, and how we separate style from HTML elements. CSS documents were created to give reference to HTML, to target them and apply styles to them. This is generally done with classes and/or IDs, which meant you could change your entire stylesheet without changing any HTML, giving the site an entirely new look at the switch of a CSS document.
Let’s rewind for a second, before CSS documents we were seeing this (inline styles that were bound to the element):
Which then became this (a class defining and attributing a specific style):
The problem now
For example, you’re used to seeing this no doubt:
This would alert the ‘text’ of the contact button. It’s safe to assume the HTML would look like this:
The class attribute has several roles in HTML: 1) As a style sheet selector (when an author wishes to assign style information to a set of elements). 2) For general purpose processing by user agents.
This is where [data-js] selectors come into play.
…and literally create some attributes on the fly. There is an argument that you shouldn’t abuse HTML5 data-* attributes, but I don’t think that’s what we’re doing with [data-js].
So why do I call it [data-js]? That’s how we target the new development concept, here’s the new HTML for that contact button earlier:
Why use [data-js] attributes?
You’re probably ready to type a bizarre comment asking me if I’ve gone crazy, but there are so many valid uses for this - and yet the concept is such an obvious one.
When creating websites, we code HTML and CSS, we create objects and components that need to do something. An interesting method of creating reusable objects is Object-Orientated CSS (OOCSS), which is several components coming together to form an entity. For instance:
Let’s revisit that:
With every new solution, not everything is perfect. Admittedly using [data-js] as a selector is slower than using classes or IDs - but can you really see 15,000+ processes a second to notice a difference?
It’s not a perfect solution; there isn’t one. We either use classes and IDs for targeting, which by now you hopefully think is a bit weird - or use the flexibility of HTML5 to create our own event hooks on elements.
For those of you who like a nice little demo, here it is. Change the styles all you want, swap classes, ID’s and completely transform the button - but of course using [data-js] it will still work flawlessly. My blog is now updated to use the [data-js] attribute methods for creating the responsive menu, check it out.
A great comment below from Kasper Mikiewicz on how to extend jQuery a little to create a nice [data-js] wrapper function!
Simply include that in your scripts file, and use like this: