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

The Vuetify table encounters a loading error when trying to retrieve data

Encountering an error with the following code 'Property "item" was accessed during render but is not defined on instance'. However, when I switch it to a normal everything functions properly. <!DOCTYPE html> <html lang="e ...

webpack-cli Configuration object is not valid

I have laravel 5.8 set up on my system and I am looking to integrate vue into it. I attempted to execute the following commands. I am using ubuntu, with node version 10.19. 1. npm install 2. npm run watch The first command executed successfully but displa ...

Display validation in HTML5 only when the form is submitted

Here is the code snippet I am referring to: <input required pattern="[0-9]{5,10}" oninput="setCustomValidity('')" oninvalid="setCustomValidity('Type something')" /> I'm looking for a way to remove o ...

Loading external Vue 3 components or plugins during runtime

I am in the process of designing an innovative architecture for the Vue 3 application that involves distributed module-based ownership. The module system will be structured using plugins, which seems to be the most suitable solution for allowing vuex modul ...

Is it possible to alter the default component directory location in VuePress to '.vuepress/components' using the register-components feature?

Attempting to incorporate a custom directory of components into vuepress using the plugin register/components has proven to be challenging. My setup looked like this: module.exports = { title: 'Hello VuePress', description: 'Just playi ...

Tips for passing a function to express-handlebars within a node.js-express application

I've been attempting to pass a function in express-handlebar, but for some reason it's not working. In my setup, I have app.js serving as the server file and index.handlebars as the handlebar file. In app.js: const express=require('expres ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants > ...

What is the best approach for organizing JavaScript/CoffeeScript in a Rails 5 project for optimal efficiency?

I am currently working on a web application with Rails 5.0.2 and I have a set of JS files for the project: https://i.stack.imgur.com/WYB23.png Each of my own JS files follows a similar pattern, like this: $(function () { var init = function () { ...

Attempting to bring in HTML through a helper, but Rails doesn't seem too thrilled about it

I have a form that triggers a remote GET request, leading to the display of a modal. The issue I'm facing is that multiple actions can utilize the same model, so I am attempting to employ a helper and jQuery to showcase different data based on what is ...

Text in SVG file misaligned at the edge

After creating an SVG with a base64 background image and two text areas for top and bottom texts, I encountered an issue on Internet Explorer and Edge. The problem is that the bottom text is aligned to the left instead of the center, and its position is in ...

During bundling, utilize an npm script to copy the package.json file to the dist directory

Currently, I am facing a challenge while trying to enhance my npm bundle script. Although the initial part is functioning smoothly, I am encountering difficulties in including three additional files along with the bundle. At present, my script looks like ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

Refreshing the page to display new data after clicking the update button

function update(){ var name= document.getElementById("TextBox").value; $.ajax({ url: '....', type: 'post', ...

Displaying elements of array in Pug template is a key task for

As a newcomer to the Jade/Pug template engine used in Express, I am faced with a challenge. I need to display the name property of each object within an associative array that is passed as a parameter to my pug template from an express route module. I hav ...

Sneaky spam and ads embedded within Joomla template

Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

Enhancing user experience with VideoJS player overlay buttons on mobile devices

I am currently using VideoJs player version 4.2. When I launch a videojs player on Safari browser in an iOS device, it defaults to native controls. However, when I pause the player, overlay buttons (links to navigate to other pages) are displayed on the v ...

limit mongoose search results to a specific year

Would it be possible to add an option for the api user to filter the wine query by year? However, if no year is specified, mongoose should not return an empty array. The same applies to the price property. For example, http://localhost:1234/api/wine?year= ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

Simply use `$timeout` inside the `$watch` method in AngularJS to create a chained

My goal is to link two $timeout functions inside a $watch. This $watch monitors user actions, and if any action is detected, both $timeout instances are canceled. Below is the code snippet outlining this scenario. .run(['$rootScope', '$loc ...

Storing values globally in NodeJS from request headers

What is the most effective way to store and access the value from a request header in multiple parts of my application? One approach could be as shown in the following example from app.js: app.get('*', (req, res) => { global.exampleHeader ...