BPOW: ESC key to close modals and menus

By July 30th, 2013

We look at some JavaScript best practice in this week's Best Practice of the Week (BPOW). Using the Esc key to close toggle-able widgets such as modals and pop-over menus is becoming so prevalent in user interfaces that it’s usually expected by users. The concept is so simple that there’s no reason not to add it into your websites and web applications.

Using the Esc key to close toggle-able widgets such as modals and pop-over menus is becoming so prevalent in user interfaces that it’s usually expected by users. The concept is so simple that there’s no reason not to add it into your websites and web applications.

If the UI widget in question has focus, we bind an event handler to the Esc key for the element in question. One important point to remember: always manage browser focus when the modal/menu is closed. In most, if not all cases, we want to place focus back on the element that opened the modal/menu.

Below is some jQuery-style pseudo code to illustrate the concept:


// This code would be placed in the method that opens the modal/menu:
$(modal_or_menu_element).keyup(function(event){
	if (event.keyCode == 27){
		// Close the modal/menu
		$(modal_or_menu_element).closeElement();

        	//  Return focus to the element that invoked it 
		$('a[href=#modal_or_menu_element_id]').focus();
	}
});

Tagged with: