Daniel
Daniel

Reputation: 15413

How to dynamically append classes

It's been some years since I have had to do DOM manipulation with CSS and vanilla JavaScript.

I have an input element some default css that is being added to its wrapping div and not the input element itself like so:

<div class="field animated-label text required">
 <label class="control-label" for="answer">Answer</label>
 <input class="form-control" />
</div>

So the default css for this input element is dictated by this selector:

.rds-form .animated-label {
  border: 2px solid #ccc;
  border-radius: 2px;
  color: #767676
  display: block;
  min-height: 40px;
  position: relative;
}

However when the user clicks out of the input element not having typed anything in, this selector gets appended on to give a red error border around the input element:

.rds-form .field-group.error, .rds-form
.field.text.error, .rds-form
.field.select.error, .rds-form .field.textarea.error {
  border: 2px solid #cc2233;
  position: relative;
}

How would this be handled in JavaScript? I am assuming this is handled by some JavaScript logic.

Upvotes: 0

Views: 297

Answers (1)

kmoser
kmoser

Reputation: 9273

Add two handlers to the <input> field:

// When the input field has focus, remove the 'error' class from .animated-label:
document.querySelector('input').addEventListener('focus', function(e) {
    document.querySelector('.animated-label').classList.remove('error');
});

// When the input field loses focus, determine whether to add or remove the 'error' class:
document.querySelector('input').addEventListener('blur', function(e) {
    if (e.target.value.match(/^\s*$/)) { // Input is empty
        document.querySelector('.animated-label').classList.add('error');
    } else {
        document.querySelector('.animated-label').classList.remove('error');
    }
});

Upvotes: 1

Related Questions