This is derived from discussion at the BADCamp 2012 Twig sprint: http://groups.drupal.org/node/265858 Please see these notes for the background.
There is a desire to have core default markup in D8 to be much cleaner, meaning that markup and classes should be removed. However, if JS is using IDs or classes to bind events, this could be problematic. There's not any rules about naming selectors to be applicable just to JS or just to CSS.
At the sprint, we thought of two potential implementations:
- A. Prefix ID or class attributes with "js"
- Example:
<div class="js-foo bar">Text</div>
For this particular div, the js-foo class is used by JS for selection. The bar class is used by CSS.
- B. Use data- attributes as selectors for JS
- Example:
<div foo="bar">Text</div>
This seems slightly unconventional given the history of how we've come to know selectors, but would be exclusive to JS.
Front-end performance is a consideration, and we'd like some input here.
We'd like to look outside of Drupal to figure out if other systems have good solutions for this; SMACSS may have some relevance.
Comments
Comment #1
ry5n CreditAttribution: ry5n commentedThe first time I ran across the idea of namespacing for js hooks was in Nicolas Gallagher's About HTML semantics and front-end architecture. It's a fantastic article; if folks are interested in SMACSS and OOCSS, it's the most compact explanation I've seen of a lot of the same ideas.
From my own experience, I do like the flexibility that data-attributes can provide. One pattern I've been using for js-driven drawers uses a trigger element with data attributes like so:
<button type="button" data-action="slide-toggle" data-target="#some-unique-element">
. Then I have a generic jQuery handler bound to anything with that data-action. It calls jQuery’s slideToggle() on the selector in data-target.In other cases, though, using data attributes is extra work and extra trouble. There is a lot of useful jQuery functionality (things like toggleClass()) that I end up missing when using data-attributes.
This is an issue where we should get input from experienced js devs to discover more use cases and pitfalls.
Comment #2
nod_BTW #1090592: [meta] Use HTML5 data-drupal-* attributes instead of #ID selectors in Drupal.settings
Comment #2.0
nod_added example?
Comment #3
nod_javascript will be using data attributes for all it's selection need. All core JS is not yet updated to do that but parts of it already are.
I guess I'll add one more column to the clean-up table in #1415788: Javascript winter clean-up.
the documentation needs to be updated: https://drupal.org/node/1887918#separate-concerns
Comment #4
nod_Comment #5
nod_Data attributes already have their issues and the js- prefixing is underway.