Skip to content

Commit

Permalink
Closing dropdown with ESC correctly sets focus to toggle (twbs#28928)
Browse files Browse the repository at this point in the history
Just firing the focus event isn't enough ... need to actually call the proper `focus()` method for it to actually do it...
  • Loading branch information
patrickhlauke authored and XhmikosR committed Jun 19, 2019
1 parent ceffc3a commit f0f7537
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion js/src/dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
39 changes: 39 additions & 0 deletions js/tests/unit/dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '<div class="tabs">' +
'<div class="dropdown">' +
'<a href="#" class="dropdown-toggle" id="toggle" data-toggle="dropdown">Dropdown</a>' +
'<div class="dropdown-menu">' +
'<a class="dropdown-item" id="item" href="#">Menu item</a>' +
'</div>' +
'</div>'
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 <input>s and <textarea>s within dropdown-menu, except for escape key', function (assert) {
assert.expect(7)
var done = assert.async()
Expand Down

0 comments on commit f0f7537

Please sign in to comment.