1

How to capture the scroll event for HTML element that using Select2? I want to capture the scroll event for dynamically adding <option> into my dropdown.

For your infomation:

  • I'm using jQuery, and the dropdown using Select2.
  • The id that of my HTML element is d. (Although the naming isn't appropriate, will rename it later)

Testing solution 1: (Not working)

$("body").on("scroll", "#select2-d-results", function(){
   alert('scroll');
})

Testing solution 2: (Not working)

$('#select2-d-results').scroll(function() {
   alert('scroll');
});

My Dropdown Selections

enter image description here

WenJun
  • 69
  • 1
  • 11

1 Answers1

2

The problem is due to the scroll event does not bubble up in DOM

Method 1

Using mousewheel event instead of scroll

Method 2 (recommended)

Using addEventListener

Jquery .on('scroll') not firing the event while scrolling

$("#d").select2();

// using on mousedown 
$("body").on("mousewheel", "#select2-d-results", function(){
   console.log('mousewheel');
})

// using addEventListener
document.addEventListener('scroll', function (event) {
    if (event.target.id === 'select2-d-results') { 
        console.log('scrolling');
    }
}, true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet" />

<select id="d" style="width: 300px">
  <option value="1">Argentina</option>
  <option value="2">Brazil</option>
  <option value="3">China</option>
  <option value="4">India</option>
  <option value="5">Indonesia</option>
  <option value="1">Argentina</option>
  <option value="2">Brazil</option>
  <option value="3">China</option>
  <option value="4">India</option>
  <option value="5">Indonesia</option>
</select>
User863
  • 19,346
  • 2
  • 17
  • 41