Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 change container position

How can I adjust the position of Select2 container so that the search box is position right over the original select element like in this website

http://www.jobnisit.com/en

It look cleaner in terms of UI in my opinion.

Ps. sorry, I can't post the image now.

like image 261
sarantoo Avatar asked Jul 22 '15 07:07

sarantoo


2 Answers

The proper way of positioning the dropdown is using the core feature provided by select2 plugin.

It provides us with 'dropdownParent' property to place to dropdown inside the particular element

select field: #edit-field-job-skillsets-tid

parent item: div.form-item-field-job-skillsets-tid

jQuery("#edit-field-job-skillsets-tid").select2(
  {dropdownParent: jQuery('div.form-item-field-job-skillsets-tid')}
 );
like image 67
jospratik Avatar answered Nov 23 '22 17:11

jospratik


There is 2 ways to do this.

1) With css:

.select2-dropdown--below {
    top: -2.8rem; /*your input height*/
}

This will not affect a container (.select2-container), but will move dropdown and search field, so you will have a desired effect.

2) With js:

$('select').select2().on('select2:open', function() {
  var container = .$('.select2-container').last();
  /*Add some css-class to container or reposition it*/
});

This code attaches a handler to 'select2:open' event, which will be fired every time when user opens a dropdown. This method is better if you have more than one select on page.

Tested with select2 4.0.0

like image 42
Gennady Dogaev Avatar answered Nov 23 '22 19:11

Gennady Dogaev