[CSS/Javascript] prefix class selector to seperate css and javascript

Sorry if break a little the “template” suggested for posting. But in fact there is a request for not only 1 but 2 related rules in 2 different languages.

The idea behind that rules is detect the non-correct usage of that technique:

CSS Names with JavaScript Hooks

  • When naming classes in HTML prefix them with ‘js-’ if they are being used in Javascript
  • when naming classes in HTML never prefix them with ‘js-’ if they are being used in CSS.

So then we seperate classes for design from classes for javascript interaction. That will avoid problems when designers uses HTML classes and change or remove them, breaking Javascript hook interaction. O viceversa: Frontend Developers changing or removing classes breaking CSS design.

So, the rules I want to suggest is:

  • For CSS/SCSS: all selectors must not start by ‘js-’
  • For Javascript: all class selectors must start by ‘js-’

There is some bibliography about the problem solved with this technique and rules.

CSS rule:

Selector must not start by ‘js-’

Selectors that starts by ‘js-’ are for javascript purposes and not for design (could be removed for non-design reasons).

Non compliant code:

 .js-header-section {
    font-size: 10pt;
}

Compliant code:

 .header-section {
    font-size: 10pt;
}

Javascript rule:

Selector must start by ‘js-’

Selectors that DO NOT starts by ‘js-’ are for design purposes and not for javascript (could be removed for design reasons).

Non compliant code:

    $('.header-section').hide();

Compliant code:

    $('.js-header-section').hide();