Luke Johnson
Author:
Luke Johnson
Date:
October 10, 2019
Ask a question
Email Luke
A fix for the jump-to-top behaviour when clicking on a Select2 select box.

Select2 is a popular plugin to enhance <select> dropdown menus. I use it in some of the platforms I develop. I have loved its functionality, but it contains an irritating bug for which I have finally found a solution:

When you scroll within a page that contains a Select2 dropdown menu, and then click on the dropdown menu, the page jumps to the top automatically, and you are forced to scroll back down the page to find your open menu.

In addition to this, Select2's default behaviour is to decided for itself whether the menu should appear above or below the select field.

These two behaviours cause a frustrating experience for users, and so I am glad to have finally found a solution.

Two simple alterations without "hacking" the source code

1. Remove transitions from Select2's container <span>

In many cases, CSS transitions may have been applied to various elements in your stylesheets -- perhaps by your own doing or by third-party libraries. It might look something like this:

span {
  transition: all 0.25s;
  -moz-transition: all 0.25s;
  -webkit-transition: all 0.25s;
  -o-transition: all 0.25s;
}

To deactive this for Select2, simply target select2's container span element:

span.select2-container {
  transition: none;
  -moz-transition: none;
  -webkit-transition: none;
  -o-transition: none;
}

This will retain your span transitions elsewhere, but will remove them specifically for Select2's container. Now your Select2s will no longer snap your page to the top of the screen.

2. Force Select2's menu to display below the <select> field

This solution was provided by Andrei Victor.

Include this javascript function in your page directly after the "select2.js" file. Then, set the dropdownPosition option to below wherever you initialize Select2.

And now, with a little CSS and JS, and with no modification to Select2's source code, you will have a Select2 plugin that behaves itself much more predictably.