Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

How to Auto Focus Modal Input Field in Vue.js

Published on December 21, 2019 53 sec read

Hi developers, sometimes we need to autofocus an input field of modal. In this short article, I’ll show how to set autofocus an input field of modal.

Template Part

We want to set focus on an input field on modal open. Let’s take a button & a modal. On click button, we’ll show the modal.

<template>
  <div id="app">
    <!-- button -->
    <button class="button" @click="showModal">Button</button>
    <!-- modal -->
    <div class="modal" v-bind:class="{'is-active':isModalOpen}">
      <div class="modal-content">
        <input type="text" ref="search" name="search">
      </div>
    </div>
  </div>
</template>

Script Part

We’ve set ref="search" in the input field. Ref is used to register or indicate a reference to the HTML element or child element in the template.

Without modal we can focus an input field using this:

this.$refs.search.focus()

To set autofocus in modal, we’ll use $nextTick() method. Please read the official documentation about $nextTick(). So, this is the code for modal:

this.$nextTick(function () {
    this.$refs.search.focus()
})

The full script looks like:

<script>
export default {
  name: 'app',
  data() {
    return {
      isModalOpen: false,
    }
  },
  methods: {
      showModal() {
          this.isModalOpen = true
          // auto focus
          this.$nextTick(function () {
              this.$refs.search.focus()
          })
      }
  },
}
</script>

That’s all. Thanks for reading. 🙂

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Leave a Reply

Your email address will not be published. Required fields are marked *