Kirk Ross
Kirk Ross

Reputation: 7153

Close Bootstrap 4 dropdown on ESC

What's the simplest way using jquery to catch the esc key to close a Bootstrap dropdown?

I know I can use $('#dropdown').dropdown('toggle') inside a keydown listener but that opens the dropdown too and 'close' doesn't seem to be a method.

Upvotes: 1

Views: 1928

Answers (1)

NooBskie
NooBskie

Reputation: 3841

Just remove the open class from the dropdown

$(document).keyup(function(e) {
     if (e.keyCode == 27) { // escape key maps to keycode `27`
        $('.navbar .dropdown').removeClass('open')
    }
});

Upvotes: 2

Related Questions