Last Updated: February 25, 2016
·
1.329K
· tyre

JS-CSS Classes

Let's say I have a button:

<a class='button'>Buy Now!</a>

So you write up some CSS for .button and everything looks pretty. You
attach some Javascript for analytics tracking or whatever and times are good.

Then you want to AB test some styling on the button. All of your JS is built with $('a.button'), but now you have .new-button with the new CSS styles. No problem, you can just ERB that JS!

<% if ab_testing(current_user.id) %>
    var button = $('a.new-button');
<% else %>
    var button = $('a.button');
<% end %>

That's a whole lotta WTF. So instead, how about this:

<a class='button js-buy-button'>Buy Now!</a>

tl;dr Prepend your Javascript selector classes and don't mix them with your styles.

4 Responses
Add your response

Nice. That's also on Github Javascript guidelines.

over 1 year ago ·

JS classname prefixes are a great idea for separating behavioural modifications from style modifications, but what about using a data-* attribute rather?
It'll keep the use of classes explicitly for styling. On top of this, you could use another data-attribute for any further variables, without polluting the classnames.

e.g.

<a href="/buy" class="button btn_primary" data-metric-type="button">Buy now</a></code></pre>
over 1 year ago ·

@ndorfin that's a great suggestion. I'm personally not a fan (aesthetically) of bracketed jQuery attribute selectors, but it would be nice to visually separate the CSS class from the JS data. Maybe a data-selectors or data-class?

over 1 year ago ·

That's the beauty of the data-* attribute, you can pick whatever name you want for the attribute.
And, with non-XHTML doctypes such as the default flavour of HTML5, you can leave the attribute value-less and the document will still be valid

e.g.

<a class="button" data-js-test>Buy now!</a></code></pre>
...could be interrogated using just the attribute name's existence:
$('[data-js-test]')...</code></pre>
over 1 year ago ·