Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a keyboard shortcut to unfocus / blur active form field?

When navigating through form inputs via TAB and SHIFT+TAB, is there a keyboard shortcut to un-focus the page (and blurring the active form input)?

Example:

Github has a lot of useful keyboard shortcuts, e.g. g p in a repository navigates to open pull requests. However, if I've clicked into a textarea I can't use website keyboard shortcuts anymore. To make keyboard shortcuts work again, I have to click (with my mouse!) outside the textarea. Is there a better way to do this in Google Chrome?

like image 764
epylinkn Avatar asked May 07 '14 20:05

epylinkn


2 Answers

This was frustrating me also.. so I made a script! This works in Tampermonkey for Chrome, should also work in Greasemonkey for Firefox.

Just press Escape to de-focus the input. It's also smart enough to only unfocus input elements.

You can choose to activate it on *github* or just on all web sites.

window.onkeydown = function(e) {
    if (e.keyCode == 27) { // Escape is 27 on my keyboard - can be modified as needed
        var focused = document.activeElement;      
        if (focused.tagName == 'INPUT' || focused.tagName == 'TEXTAREA') {
            focused.blur();
        }
    }
};

Hope you're able to receive this since it's been several months.

like image 162
sricks Avatar answered Sep 23 '22 16:09

sricks


since KeyboardEvent.keyCode has been deprecated and is not recommended although some browsers may still support, here's the actual working code (which is an update to the code originally posted by sricks above)

(function () {
  window.onkeydown = function (e) {
    if (e.code === 'Escape') {
      const focused = document.activeElement;
      const elems = ['INPUT', 'TEXTAREA'];
      if (elems.includes(focused.tagName)) {
        focused.blur();
      }
    }
  };
}());
like image 30
Arun Karnati Avatar answered Sep 23 '22 16:09

Arun Karnati