Rechercher

Une liste déroulante personnalisée en JS + CSS

Placeholder image

Personnaliser le style d’un selecteur avec un peu de JS et de CSS.

const selectsContainers =  document.querySelectorAll('.select-container');
const selects = document.querySelectorAll('select');
const change = new Event("change");
// create the links & anchors
if(selects.length > 0) {
  document.addEventListener("DOMContentLoaded", function() {
      for (var i = 0; i < selectsContainers.length; i++) {
        let childrens = selects[i].children;
        let dropdown  = document.createElement('div');
        dropdown.setAttribute('id', 'select-' + selects[i].getAttribute('id'));
        dropdown.setAttribute('class', 'select-stylized');
        let dropdownSelected = document.createElement('span');
        dropdownSelected.setAttribute('id', 'selected-' + selects[i].getAttribute('id'));
        dropdownSelected.setAttribute('class', 'empty');
        dropdownSelected.innerText = childrens[0].innerText;
        dropdown.appendChild(dropdownSelected);
        let dropdownUl = document.createElement('ul');
        for (var j = 1; j < childrens.length; j++) {
          let option = document.createElement('li');
          option.innerText = childrens[j].innerText;
          option.setAttribute('data-value', childrens[j].getAttribute('value'));
          option.setAttribute('data-select', selects[i].getAttribute('id'));
          option.addEventListener("click", function() {
            document.getElementById(option.getAttribute('data-select')).value =  option.getAttribute('data-value');
            document.getElementById(option.getAttribute('data-select')).dispatchEvent(change);
            document.getElementById('selected-' + option.getAttribute('data-select')).innerText = option.getAttribute('data-value');
            document.getElementById('selected-' + option.getAttribute('data-select')).classList.remove("empty");
          })
          dropdownUl.appendChild(option);
        }
        dropdown.appendChild(dropdownUl);
        dropdown.addEventListener("click", function() {
          dropdown.classList.toggle('open');
          let selectsOpen = document.querySelectorAll('.select-stylized.open');
          for (var h = 0; h < selectsOpen.length; h++) {
            if(selectsOpen[h] != dropdown ) {
              selectsOpen[h].classList.remove('open');
            }
          }
        })
        selectsContainers[i].insertBefore(dropdown, selects[i]);
      }
  });
}