From 81b7b76a7c0b6d9bf4e5ee7482efa66cd6cca554 Mon Sep 17 00:00:00 2001
From: Piotr Delawski <piotr.delawski@xwp.co>
Date: Thu, 10 Mar 2016 14:48:05 +0100
Subject: [PATCH] Fix `focus()` inside widget customize control (try to focus
 on form elements first, then on anchors and other elements).

---
 src/wp-admin/js/customize-controls.js | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/src/wp-admin/js/customize-controls.js b/src/wp-admin/js/customize-controls.js
index dbda12b..9be6b2b 100644
--- a/src/wp-admin/js/customize-controls.js
+++ b/src/wp-admin/js/customize-controls.js
@@ -81,7 +81,7 @@
 		construct = this;
 		params = params || {};
 		focus = function () {
-			var focusContainer;
+			var focusContainer, focusElement;
 			if ( construct.extended( api.Panel ) && construct.expanded && construct.expanded() ) {
 				focusContainer = construct.container.find( 'ul.control-panel-content' );
 			} else if ( construct.extended( api.Section ) && construct.expanded && construct.expanded() ) {
@@ -91,7 +91,13 @@
 			}
 
 			// Note that we can't use :focusable due to a jQuery UI issue. See: https://github.com/jquery/jquery-ui/pull/1583
-			focusContainer.find( 'input, select, textarea, button, object, a[href], [tabindex]' ).filter( ':visible' ).first().focus();
+			focusElement = focusContainer.find( 'input, select, textarea, button' ).filter( ':visible' ).first();
+			// Focus on objects, links and other element only if no form element/input was found 
+			if ( 0 === focusElement.length ) {
+				focusElement = focusContainer.find( 'object, a[href], [tabindex]' ).filter( ':visible' ).first();
+			}
+			focusElement.focus();
+
 		};
 		if ( params.completeCallback ) {
 			completeCallback = params.completeCallback;
