0

Is it good practice to express the state of an HTML element--such as whether an input's value is valid--using a CSS class? Would it be better practice to use data attributes, the properties of a JavaScript object representing the element, or some other method? Example:

CSS:

.error {
    box-shadow: 0 0 8px .1em #b94a48;
}

.error is appended to any input that fails validation. When the user attempts to proceed, jQuery checks for the class:

JavaScript:

if ($('#container').find('.error').length !== 0) {
    // Don't proceed.
}
  • Short answer: yes. – Jules Aug 31 '17 at 23:43
  • Slightly longer answer: This sort of thing tends to happen a lot when using jQuery. It's fairly common practice. If using a larger frontend framework, then state would probably be handled by that and not by CSS class. – neilsimp1 Sep 1 '17 at 15:50
  • 3
    If you wish to achieve WCAG compliance, or if you wish to cater to people with disabilities, use of only color to indicate an error will leave out people who are blind or colorblind. In addition to adding the .error class, consider using aria-invalid as well as a non-color-based visual indicator, such as an exclamation point adjacent to the field. – John Wu Sep 2 '17 at 1:54
  • 1
    As a color blind developer, I can attest to this. I can barely tell the success green and the error red look apart in the recent project I've been working on. Thanks for the suggestion. – Allie Fitter Sep 2 '17 at 2:02
3

Using classes to track state is pretty common, for example - in AngularJS: https://docs.angularjs.org/api/ng/directive/form#css-classes

but - remember that css-classes are easily manipulated in the browser, so if you're doing anything other than decoration with the state classes, you may want to consider also saving state in a data-attribute as well (or controller if using a framework)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.