As per title, is there a way to force select2 to always create a dropdown instead of a drop-up?
There also appears to be some javascript that is either causing the flip when you scroll above the dropdown, adding a new CSS class "select2-drop-above", or both.
EDIT: I should've specified that I'm pulling the library in via select2-rails. I'm hoping there is a way around this that doesn't involve pulling the whole select2 lib in myself and editing the select2.js file directly.
Updated from [shanabus] answer
Since modifying the source code is not an option and adding a hook to the
select2:open
event is not very elegant, especially when you have multiple select2 instances in the same page, I have written a small extension for theSelect2
plugin.My implementation is inspired by a PR from the plugin's repository (https://github.com/select2/select2/pull/4618) that is not yet merged.
Basically, the following code overrides the original plugin function that handles the dropdown positioning and adds a new option (
dropdownPosition
) to force the dropdown positioning above/below.The new
dropdownPosition
option can take the following values: -below
- the dropdown is always displayed at the bottom of the input; -above
- the dropdown is always displayed at the top of the input; -auto
(default) - it uses the old behavior.Just insert the following code after
select2.js
file:The initialize the plugin with as follows:
Fiddle here: https://jsfiddle.net/byxj73ov/
Github repository: https://github.com/andreivictor/select2-dropdownPosition
You can do it by overwriting CSS like so:
I used to find an easier/faster solution for that:
It's simple, you just change the .select2-dropdown--above to .select2-dropdown--below in the opening event (select2:open).
It will only works under the event, and there could be many other ways to perform it just changing classes when the select is opened.
ps. It won't work if you try to populate your select using jquery.
You can just edit
select2.js
Where it says
just change it to
Modifying the plugin is not preferred as you mention. I had a similar issue and couldn't find an way to use
select2
options to force the dropdown to stay below. The solution I ended up with is the following:This code determines if there is enough room to place the dropdown at the bottom and if not, creates it by adding margin-bottom to some element on the page. It then scrolls to just above the select2 so that the dropdown won't flip.