Taha

How to Add Focused State to Your Input Component

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>
Taha Shashtari

I'm Taha Shashtari, a full-stack web developer. Building for the web is my passion. Teaching people how to do that is what I like the most. I like to explore new techniques and tools to help me and others write better code.

Subscribe to get latest updates about my work
©2024 Taha Shashtari. All rights reserved.