1

I am trying to check if an element has focus, in my case Input, and add a class to another element. This is what I am trying, but I am not sure why hasFocus() is not working.

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

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

I am trying to do this in a Vue.js custom directive.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Teni
  • 45
  • 1
  • 1
  • 6
  • Does it work if you manually execute these statements in the dev console? – David Weldon Jan 15 '20 at 16:16
  • @DavidWeldon only if i call document.hasFocus(). So probably works only for the document instead of single element. So what i am trying is to find other alternative if possible – Teni Jan 15 '20 at 16:22
  • According to [this](https://stackoverflow.com/questions/497094) you should be looking for `document.activeElement`. – David Weldon Jan 15 '20 at 16:33

2 Answers2

1

There is a suggestion in the Vue.js forum to use the focusin event:

created() {
  document.addEventListener('focusin', this.focusChanged)
},
beforeDestroy() {
  document.removeEventListener('focusin', this.focusChanged)
},
methods: {
  focusChanged (event) {
    const el = event.target
    // do something with the element.
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
makkus
  • 383
  • 4
  • 11
-1

Since I mentioned that I need to make it as a custom directive:

This is how I fixed it.

class someClassName {
  constructor (el, config = {}) {
    this.el = el
    this.input = el.querySelector('.a-input')
    this.button = el.querySelector('.a-button')

    this.onInputFocus = this.onInputFocus.bind(this)

    this.attachEvents()
  }

  onInputFocus () {
    this.button.classList.add('testclass')
  }

  attachEvents () {
    this.input.addEventListener('focus', this.onInputFocus)
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Teni
  • 45
  • 1
  • 1
  • 6