Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expected.

onFocus () {
    let isFocused = document.el.querySelector('a-input');
    let focusedEl = document.el.querySelector('a-button');

    if(isFocused.hasFocus()) {
      focusedEl.classList.add('testClass');
    }
  }

I'm trying to implement this functionality within a custom directive in Vue.js.

Answer №1

Check out a helpful tip from the Vue.js community in this topic on the forum. They suggest using the focusin event:

During the 'created' lifecycle hook:
  document.addEventListener('focusin', this.focusChanged)
After 'beforeDestroy':
  document.removeEventListener('focusin', this.focusChanged)
Methods include:
  focusChanged (event) {
    const el = event.target
    // Handle element focus change here.
  }
}

Answer №2

After considering the necessity of creating a custom directive:

This is my solution.

class customizedDirective {
  constructor (element, settings = {}) {
    this.element = element
    this.inputField = element.querySelector('.custom-input')
    this.actionButton = element.querySelector('.custom-button')

    this.onInputFieldFocus = this.onInputFieldFocus.bind(this)

    this.bindEvents()
  }

  onInputFieldFocus () {
    this.actionButton.classList.add('special-class')
  }

  bindEvents () {
    this.inputField.addEventListener('focus', this.onInputFieldFocus)
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is returned by jQuery when it fails to locate a specified class selector within the jQuery object?

Picture this scenario: var $letsTestA = $( '.lets-test-a' ), $letsTestB = $( '.lets-test-b' ); Then, consider this HTML: <div class="lets-test-a"></div> (I omitted .lets-test-b intentionally) Now, what happens if we ...

What is the reason for the error message "vue","v-for","item is not defined"?

Here is my code in HTML. I am encountering an issue when using 'v-for' where it says 'item is not defined'. <form action=""> <div class=" form-group"> <tr> &l ...

Utilizing variable values in Google Charts with AngularJS

Hello everyone, I am attempting to display a chart using data obtained from an API. The output of the API is in the form of List<String> and not in JSON format. Here is the snippet of my JS file: google.load('visualization', '1', ...

Tips for managing a basic click event within the Backbone.js framework

I am facing a challenge with a basic functionality in Backbone. I am trying to set up the <h1> element on my page so that when a user clicks on it, it smoothly navigates back to the homepage without a page reload. Here is the HTML snippet: <h1& ...

Adding additional rows to an Array Object in JavaScript based on a certain condition

I am faced with a scenario where I have an array object structured as follows [ { id: 123, startdate: '2022-06-05', enddate: '2023-04-05' },{ id: 123, startdate: '2021-06-05', enddate: '2021-04-05' } ] The task at h ...

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Nextjs optimizing page caching to reduce unnecessary rendering

Within my Next.js application, I have implemented two unique pages. Each page is designed to display a randomly selected person's name when the component is initially loaded. simpsons.tsx export default function Simpsons() { const [person, setPerso ...

Troubleshooting problems during Vue setup

Just diving into Vue development and hitting a roadblock. Here's what I've done so far: I followed the installation guide on the Vue 3 documentation, which can be found at the following link: https://v3.vuejs.org/guide/installation.html#npm I ...

Display the outcome of a POST request on the webpage

Currently working with node.js/express and have a view that includes a form. This form POSTs to a route which returns JSON data. I want to be able to submit the form and display the returned data underneath the form on the same view without refreshing the ...

There are various IDs in the output and I only require one specific ID

I have a JSON fetcher that is functioning properly. However, whenever I request an ID, it returns all the IDs present in the JSON data. Is there a way to retrieve only the latest ID? This is my first time working with JSON so I am still learning. $(docu ...

Prevent draggable functionality of jQuery UI on elements with a specific class

I have created a dynamic cart feature where users can drag and drop items into the cart. However, once an item is placed in the cart, it should no longer be draggable (though still visible but faded). I attempted to achieve this by using the following code ...

The browser is preventing files from being accessed through Express because they do not have the text/html MIME type

Currently, I am attempting to set up a nodejs express web server with a static frontend. In order to handle the GET requests made to /, I have implemented myServer.use(express.static("public"));. Within the public folder are HTML, JavaScript, CSS, and im ...

Scaling Images using HTML and CSS

Hey there, I'm currently learning web development and running into a bit of trouble with creating responsive images. Can anyone give me some guidance on what changes I should make in the code below? Here's the HTML code: <div class="caro ...

Masking input text to allow numbers only using either javascript or jquery

I have experience with javascript and jquery. My goal is to create a masking template for <input type="text"> This template should only accept numbers and automatically format the input with dashes after every two numbers typed. The desi ...

In need of assistance with filtering lists using JQuery

Hi there! I'm looking to modify a list filtering function by targeting multiple ul tags within the same div instead of just filtering li elements. Any ideas on how this can be achieved? Below is my JavaScript code: $( document ).ready(function() { ...

Uncovering the hidden treasures of checkbox values using jQuery

I've encountered an issue with a form containing checkboxes. Some values are meant to be true by default, so I've hidden them using the following method: <input type=checkbox name="<%= _key %>" checked="checked" style="display:none" /& ...

The onMounted function is invoked in the absence of any existing component instance that can be linked with

React/Angular component <template> <h1>ANOTHER-USER-PAGE</h1> <button @click="changeRoute(`/other/1`)">OTHER 1</button> <button @click="changeRoute(`/other/2`)">OTHER 2</button> ...

What is the better choice in NodeJS: using "return cb(..)" or first calling cb(..) and then returning?

Forgive me if this sounds like a silly question, but I'm curious about the implications of something: Whenever I encounter an error or need to complete a function flow, I follow certain instructions such as: if(err) { cb(err); // or for exampl ...

The background-size:cover property fails to function properly on iPhone models 4 and 5

I have taken on the task of educating my younger sister about programming, and we collaborated on creating this project together. Nicki Minaj Website However, we encountered an issue where the background image does not fully cover the screen when using b ...