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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Thalecress
  • 3,231
  • 9
  • 35
  • 47

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
  • 23,044
  • 10
  • 62
  • 76
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
  • 5,162
  • 9
  • 47
  • 76