twbs / bootstrap

The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.
https://getbootstrap.com
MIT License
170.19k stars 78.78k forks source link

Dropdown: add an option to prevent focus on toggler via js show() #37977

Open dp-sgr opened 1 year ago

dp-sgr commented 1 year ago

Prerequisites

Proposal

Add an options object or similar to the show() method of an dropdown instance. Via the options we could simply configure if the show method should focus the toggler of the dropdown or not.

Something like that would be very nice:

let dropdownInstance = window.bootstrap.Dropdown.getOrCreateInstance(togglerElement);

dropdownInstance.show({
   preventFocus: true
});

As a possible workaround i currently implemented this hack:

let dropdownInstance = window.bootstrap.Dropdown.getOrCreateInstance(togglerElement);

let focusFunc = togglerElement.focus;
togglerElement.focus = () => {
    /*do nothing*/
};

try {
    dropdownInstance.show();
} finally {
    togglerElement.focus = focusFunc;
}

Motivation and context

In some scenarious we don't want the toggler to be focused on dropdown show. In our specific use-case we have a custom autocomplete component which simply is a input-group of an text input and the dropdown toggler button.

By inserting chars to the text input (with a specific debounce time) the dropdown should be showed. But this currently leads to the issue of focusing the toggler.

https://github.com/twbs/bootstrap/blob/c735b2e196544b3bba25d645f4d725e8667b106c/js/src/dropdown.js#L151

MaruthiKo commented 1 year ago

Hi, I would like to work on this issue

mdo commented 1 year ago

/cc @GeoSot @patrickhlauke

patrickhlauke commented 1 year ago

i'd be conceptually ok with this (provided that an author who suppresses the automatic focus handling definitely implements their own focus handling, which is something we can reinforce in the docs)