Monthly Archives: January 2015

JQuery HTML5 custom attributes

I came across what looks to be a good solution to managing UI elements (visibility, opacity, etc.) without resorting to burying styles in an attached CSS file. With HTML5, you can use custom attributes prefaced with “data-”, e.g:

<h1 data-groups="foo, bar">I have a session code</h1>

<p data-groups="bar">Enter it here to join a session</p>

You can extract that data, for example:

<div id="divNewSession" data-groups="foo">
var groupData = $("#divNewSession").data("groups");

Which would generally only make sense with something specific, such as a the DIV in this example. But you could also act globally on various elements that all share a data attribute, such as making them all invisible. You can even differentiate with keyword searches or a wildcard (contains) search:

// Any element with a data-group attribute containing "foo" will be affected
$("*[data-groups*='foo']").css("background", "black");

// Any element with a data-group attribute only containing "bar" will be affected
$("*[data-groups='bar']").css("background", "red");

Note the * after groups in the first example. This will act on any element even if the data-groups attribute contains more than just “foo”. Also pay careful attention to the use of double vs. single quotes. IE and Chrome didn’t care, but Safari did.

I like this approach because:

  • It’s easy to see the relationship between an element and an attribute
  • The relationship isn’t buried in an external CSS file or deep within a pile of javascript code
  • It doesn’t clutter up a CSS file with miscellaneous styles used just to control temporary states, e.g:
    #divNewSession { visibility: collapse; }
  • It’s flexible. An element might be affected in one case, ignored in another.
  • Use of a custom attribute avoids confusion or collisions with any other code or namespaces