Search code examples
javascriptdom-events

JavaScript keydown event: can I tell what element previously had focus?


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?


Solution

  • 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;
    });