1

When a user was focused on a particular element when they pressed the tab key, I want to execute a particular function. But I don't want to this function to execute unless that particular element had focus when the tab key was pressed.

Is there a way to to tell what element had (has?) focus from the keydown event itself? Or should I set a particularElementHasFocus property in response to onBlur and onFocus events on that element?

Thalecress
  • 3,061
  • 9
  • 32
  • 44

2 Answers2

1

You can use document.activeElement to get current focused element. or use following code

var particularElementHasFocus  ;
$('input, textarea, button').focus(function() {
  particularElementHasFocus = this;
});

$('input, textarea, button').blur(function() {
  particularElementHasFocus = null;
});
Anoop
  • 22,496
  • 10
  • 60
  • 70
0

Using jQuery it could be done by testing the .focus of the element in question. With standard JS you can use document.activeElement - https://developer.mozilla.org/en-US/docs/DOM/document.activeElement

Fluidbyte
  • 4,982
  • 7
  • 42
  • 72