JS select2 plugin not scrolling when options are open
Asked Answered
W

1

8

I am using JS Select2 library to use as multiple options select. The select is positioned within a div which is scrolled by its parent div with css - overflow-y: scroll. The nested div scrolls fine until an option is opened. When options are opened then the div becomes un-scrollable unless it is scrolled on the select options. Not sure if the source of the problem is my html/css or its the select2 lib.

Thanks in advance for any help!

My markup:

<div id="topcontainer" style="padding-top: 100px; overflow-y: scroll;  position: absolute; height: 1000px; width: 500px; background: #6d3353">
<div id="parent" style="position: relative; height: 3000px; width: 200px; background: #e4b9b9">
    <select class="js-example-basic-multiple" name="states[]" multiple="multiple">
        <option value="AL">aaaaaaa</option>
        <option value="AL">bbbbbbb</option>
        <option value="AL">ccccccc</option>
        <option value="WY">ddddddd</option>
    </select>
    <script>

        $(document).ready(function () {
            $('.js-example-basic-multiple').select2();
        });
    </script>
</div>

Whirligig answered 31/3, 2019 at 10:31 Comment(0)
I
24

Select2 intercept the scroll as you can see in the select2 source code.

I think its not a problem but a feature, because when you have it opened you want to scroll it, not the parents.

Anyway, looking at select2 events I found that we can override it by using the "select2:open" event and removing the added "scroll.select2" namespace events.

Example:

     $('#states').select2({
         dropdownParent: $('#parent')
      });
      $('#states').on('select2:open', function (e) {
        const evt = "scroll.select2";
        $(e.target).parents().off(evt);
        $(window).off(evt);
      });

You may test it here: Jsbin

Insistency answered 31/3, 2019 at 11:44 Comment(1)
Thanks for the answer, worked like a charm! You're said that "you want to scroll it, not the parents." but in my case, with your solution behaves as a nested scroll which is exactly what I need. Excellent!Whirligig

© 2022 - 2024 — McMap. All rights reserved.