How to Add Focused State to Your Input Component

May 15 2018 | By Taha Shashtari

If you're building your own input component, it's very likely that you would need to display it differently when the input is focused on.

For example, when the user focuses on the input, the color of the label above it, and the border color of the input should change.

The easiest way to do this is by adding .focused class to the root element of the input component. And then we'll scope our css selectors with that class to style it for the focused state.

Finally, let's see this example in code:

<template>
  <div
    :class="{ 'focused': focused }"
    class="textfield"
  >
    <label class="label">
        Input Label
    </label>
    <input
      class="input"
      type="text"
      @focus="focused = true"
      @blur="focused = false"
    >
  </div>
</template>

<script>
export default {
  data () {
    return {
      focused: false
    }
  }
}
</script>

<style scoped>
.textfield.focused .label {
  color: red;
}

.textfield.focused .input {
  border: 1px solid red;
}
</style>