From: Patrick H. Lauke Date: Wed, 19 Jun 2019 09:23:41 +0000 (+0100) Subject: Closing dropdown with ESC correctly sets focus to toggle (#28928) X-Git-Tag: v5.0.0-alpha1~1053 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f0f75379f661587936fdcf7138fe9805838b7a01;p=thirdparty%2Fbootstrap.git Closing dropdown with ESC correctly sets focus to toggle (#28928) Just firing the focus event isn't enough ... need to actually call the proper `focus()` method for it to actually do it... --- diff --git a/js/src/dropdown.js b/js/src/dropdown.js index 6bae6a4b40..729b64732a 100644 --- a/js/src/dropdown.js +++ b/js/src/dropdown.js @@ -486,7 +486,7 @@ class Dropdown { if (!isActive || isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) { if (event.which === ESCAPE_KEYCODE) { - EventHandler.trigger(SelectorEngine.findOne(Selector.DATA_TOGGLE, parent), 'focus') + SelectorEngine.findOne(Selector.DATA_TOGGLE, parent).focus() } Dropdown._clearMenus() diff --git a/js/tests/unit/dropdown.js b/js/tests/unit/dropdown.js index 63f83b3bb6..ab0fdbd444 100644 --- a/js/tests/unit/dropdown.js +++ b/js/tests/unit/dropdown.js @@ -765,6 +765,45 @@ $(function () { $triggerDropdown[0].dispatchEvent(new Event('click')) }) + QUnit.test('should close dropdown and set focus back to toggle when escape is pressed while focused on a dropdown item', function (assert) { + assert.expect(3) + var done = assert.async() + + var dropdownHTML = '
' + + '' + var $dropdown = $(dropdownHTML) + .appendTo('#qunit-fixture') + .find('[data-toggle="dropdown"]') + .bootstrapDropdown() + + var $item = $('#item') + var $toggle = $('#toggle') + + $dropdown + .parent('.dropdown') + .on('shown.bs.dropdown', function () { + // Forcibly focus first item + $item.focus() + assert.ok($(document.activeElement)[0] === $item[0], 'menu item initial focus set') + + // Key escape + var keydown = new Event('keydown') + keydown.which = 27 + $item[0].dispatchEvent(keydown) + + assert.ok(!$dropdown.parent('.dropdown').hasClass('show'), 'dropdown menu was closed after escape') + assert.ok($(document.activeElement)[0] === $toggle[0], 'toggle has focus again once menu was closed after escape') + done() + }) + + $dropdown[0].dispatchEvent(new Event('click')) + }) + QUnit.test('should ignore keyboard events for s and