javascriptjquery-uijquery-select2

Scroll an option into view on open


I have a select with months.

The most used is April, so I'd like to present it when the user open the select when nothing else is chosen already.

I have a solution that works well in Chrome (the option list scrolls so that April is the first visible), but in FireFox and Safari the whole page is scrolled (April s shown at the top of the page).

$('#example').select2({
  placeholder: 'Select a month'
})

$('#example')
  .on('select2:open',
    (e) => {
      if (!e.target.value) {
        setTimeout(function () {
          const opt800 = $('.select2-results__option[data-select2-id$="APR"]')[0]
          if (opt800) {
            opt800.scrollIntoView({ behavior: 'smooth', container: 'nearest' })
          }
        }, 1)
      }
    })

https://jsfiddle.net/94kdgahq/2/

EDIT: thanks to the suggestions here, I managed to get it to work with

const container = $(".select2-results__options")[0];
const boundingRect = $('.select2-search.select2-search--dropdown')[0].getBoundingClientRect();
container && container.scrollTo(0, (opt800.offsetTop - boundingRect.height));

Solution

  • $('#example').select2({
        placeholder: 'Select a month'
    });
    
          $('#example')
            .on('select2:open',
              (e) => {
                if (!e.target.value) {
                  setTimeout(function () {
                    const opt800 = $('.select2-results__option[data-select2-id$="APR"]')[0];
                    if (opt800) {
                      var optionTop = opt800.offsetTop
                      document.querySelectorAll('#select2-example-results')[0].scrollTop = optionTop - (document.querySelector('.select2-results__option').offsetHeight + 5);
                    }
                  }, 1);
                }
              })