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.
}
asked Aug 31, 2017 at 23:40
4
  • Short answer: yes. Commented Aug 31, 2017 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. Commented Sep 1, 2017 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. Commented Sep 2, 2017 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. Commented Sep 2, 2017 at 2:02

1 Answer 1

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)

answered Sep 1, 2017 at 16:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.