Skip to content

Placeholder width is 0px when select2 is initialized #3292

@brandonhall

Description

@brandonhall

We have a Backbone app which inits select2 before it is visible on the page. As a result, the select2-search__field width is always 0px because that's the innerWidth when it's initialized. This caused placeholders to be hidden.

Here's the relevant block of code in select2...

 if (this.$search.attr('placeholder') !== '') {
  width = this.$selection.find('.select2-selection__rendered').innerWidth();
} else {
  var minimumWidth = this.$search.val().length + 1;
  width = (minimumWidth * 0.75) + 'em';
}

As a result, the solution was to use setTimeout which initialized select2 after it was visible on the page
but that causes all sorts of bouncing around on the page as the elements are initialized.

I added an OR condition to use 100% if innerWidth is 0 to prevent this. Like so: width = this.$selection.find('.select2-selection__rendered').innerWidth() || '100%'

I'm not sure it's the preferred solution but it does the job and fixes the issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions