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.

3
  • Does it work if you manually execute these statements in the dev console? Jan 15, 2020 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, 2020 at 16:22
  • According to this you should be looking for document.activeElement. Jan 15, 2020 at 16:33

2 Answers 2

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.
  }
}
-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)
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.