walterdesign
walterdesign

Reputation: 105

Malihu jQuery Custom Scrollbar with Select 2

Scrollbar shows only on first opening and no more. What I did wrong?

$('.select').on('select2:open', function () {
    function showScroll() {
        $('.select2-results__options').mCustomScrollbar();
    }
    setTimeout(showScroll, 1);
});

Upvotes: 4

Views: 5039

Answers (3)

mshahbazm
mshahbazm

Reputation: 611

The selected answer did not work for me, so I came up with following solution:

$('.your-select2-element').on('select2:open', function (e) {
     setTimeout(function () {
          $('.select2-results > ul').mCustomScrollbar();
     },100); /* if there are multiple select2 instances on a page, timeout makes sure right drop down is being targeted*/
});
$('.your-select2-element').on('select2:closing', function (e) {
     $('.select2-results > ul').mCustomScrollbar("destroy");
});

In case you wondering why the '.select2-results > ul' selector ?

Well every time select2 drowndown is opened, it dynamically appends html at the very end of body tag and the list that holds all of the options, its wrapped inside '.select2-results'. And when this dropdown is closed, this dynamically added html is removed.

Upvotes: 0

Filip Wroński
Filip Wroński

Reputation: 356

This solution works for me:

$('select').on('select2:open', function (e) {
 $('.select2-results__options').mCustomScrollbar('destroy');
  setTimeout(function () {
    $('.select2-results__options').mCustomScrollbar();
  }, 0);
});

Upvotes: 1

walterdesign
walterdesign

Reputation: 105

I found a solution:

$('.select').on('select2:open', function () {
    $('.select__dropdown .select2-results__options').mCustomScrollbar('destroy');
    $('.select__dropdown .select2-results__options').mCustomScrollbar('update');
    setTimeout(function() {
        $('.select__dropdown .select2-results__options').mCustomScrollbar({
            axis: 'y',
            scrollbarPosition: 'inside',
            advanced:{
                updateOnContentResize: true
            },
            live: true
        });
    }, 0);
});

Upvotes: 5

Related Questions