Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">
<main>
        <h1>Simple example</h1>
        <div id="mySelect"></div>
    </main>
              
            
!

CSS

              
                  * {
            box-sizing: border-box;
        }
body{
  background-color:#ccc;
  margin-top:80px;
}
        main {
          font-family: 'Roboto Slab', serif;
            display: flex;
            width: 600px;
            margin: 0 auto;
            flex-direction: column;
        }
        #mySelectVanilla {
            border: 1px solid rgb(206, 206, 206);
            color: rgb(255, 255, 255);
            background: linear-gradient(to right, rgb(15, 12, 41), rgb(48, 43, 99), rgb(36, 36, 62));
            width: 100%;
        }
        .select__opcoes.open {
            display: block;
        }
.wrapper-select {
  position: relative;
  width: 100%;
  font-family: "Source Sans Pro", Helvetica, Arial, Sans-Serif;
}
.wrapper-select input {
  display: none;
}
.select__atual {
  height: 50px;
  width: 100%;
  cursor: pointer;
  border: 1px solid;
  display: flex;
  align-items: center;
  padding: 0 15px;
  position: relative;
}
.select__atual.open {
  border-bottom: none;
}
.select__icon {
  position: absolute;
  right: 15px;
  color: #e2264d;
}
.select__opcoes {
  width: 100%;
  display: none;
  border: 1px solid;
  border-top: none;
  border-color: #cecece;
}
.select__opcoes__label {
  display: flex;
  height: 50px;
  width: 100%;
  align-items: center;
  padding: 0 15px;
  cursor: pointer;
}
.select__opcoes__label:hover {
  color: #fff;
  background-color: rgba(0, 0, 0, 0.7);
}
              
            
!

JS

              
                jQuery.fn.customSelect = function(options) {
  function chooseOption(obj) {
    var selectOption = obj.find(".select__opcoes__label");

    selectOption.click(function() {
      var selectName = $(this).text();
      obj.find(".select__atual__text").text(selectName);
      obj.find(".select__opcoes").hide();
    });
  }

  function closeSelect(obj) {
    $("body").click(function(event) {
      if (!$(event.target).closest(obj).length) {
        obj.find($(".select__opcoes")).hide();
      }
    });
  }

  function openSelect(obj) {
    var selectBox = obj.find(".select__atual");

    selectBox.click(function() {
      $(this).toggleClass("open");
      obj.find(".select__opcoes").toggle();
    });
  }

  function appendOption(obj) {
    var list = settings.list;
    var lista = [];
    var listaIds = [];

    $.each(list, function(i, elem) {
      var id = elem
        .replace(/ /g, "")
        .replace(/[^\w\s]/gi, "")
        .toLowerCase();

      listaIds.push(
        `<input type="radio" id="${id}" value="${elem}" name="optSelect">`
      );
      lista.push(
        `<label class="select__opcoes__label" for="${id}">${elem}</label>`
      );
    });

    obj.find(".wrapper-select").prepend(listaIds);
    obj.find(".select__opcoes").append(lista);
  }

  var settings = $.extend(
    {
      border: "1px solid red",
      list: ["Option 1", "Option 2"],
      defaultText: "Choose an option",
      textColor: "#fff",
      bgColor: "linear-gradient(to right, #0f0c29, #302b63, #24243e)",
      width: "100%",
      icon: "❤"
    },
    options
  );

  return this.each(function(i, elem) {
    $(this)
      .append(
        `<div class="wrapper-select">
                  <div class="select__atual">
                  <span class="select__atual__text">${
                    settings.defaultText
                  }</span>
                  <span class="select__icon">${settings.icon}</span>
                  </div>
                  <div class="select__opcoes"></div>
                  </div>`
      )
      .css({
        border: settings.border,
        color: settings.textColor,
        background: settings.bgColor,
        width: settings.width
      })
      .click(appendOption($(this)))
      .click(openSelect($(this)))
      .click(chooseOption($(this)))
      .click(closeSelect($(this)));
  });
};

// Create an immediately invoked functional expression to wrap our code
(function() {
  // Define our constructor
  this.heliosSelect = function(obj, items) {
    // Create global element references
    this.obj = obj;
    this.items = items;

    // Define option defaults
    /* First we create global element references. These are important so that we can reference pieces of the Modal from anywhere in our plugin. */

    var defaults = {
      defaultText: "Choose an option",
      list: items
    };

    // Create options by extending defaults with the passed in arugments
    /* Next up, we add a default options object. If a user doesn't provide options, we use these. */
    if (arguments[0] && typeof arguments[0] === "object") {
      this.options = extendDefaults(defaults, arguments[0]);
    }
  };

  // Métodos Private
  function buildSelect() {
    /*Pega o objeto passado na chamada do plugin*/
    let objInicial = this.obj;
    let objConversao = objInicial.replace("#", "");
    let objFinal = document.getElementById(objConversao);

    /*Cria o DOM da lista*/

    /* Eu utilizo o createDocumentFragment para dar um appendChild de tudo no objFinal */
    let frag = document.createDocumentFragment();

    let fragWrapper = frag.appendChild(document.createElement("div"));
    fragWrapper.className = "wrapper-select";

    let fragSelectAtual = fragWrapper.appendChild(
      document.createElement("div")
    );
    fragSelectAtual.className = "select__atual";

    let selectAtualText = fragSelectAtual.appendChild(
      document.createElement("span")
    );

    selectAtualText.className = "select__atual__text";

    let selectIcon = fragSelectAtual.appendChild(
      document.createElement("span")
    );

    selectIcon.className = "select__icon";

    let selectOpcoes = fragWrapper.appendChild(document.createElement("div"));

    selectOpcoes.className = "select__opcoes";

    fragSelectAtual.onclick = function() {
      fragSelectAtual.classList.toggle("open");
      selectOpcoes.classList.toggle("open");
    };

    let items = this.items;
    let itemsId = [];

    for (let index = 0; index < items.items.length; index++) {
      const element = items.items[index];
      let radioLabel = selectOpcoes.appendChild(
        document.createElement("label")
      );
      radioLabel.className = "select__opcoes__label";
      radioLabel.setAttribute("for", element);
      radioLabel.textContent = element;

      let inputRadio = fragWrapper.insertBefore(
        document.createElement("input"),
        fragSelectAtual
      );

      inputRadio.setAttribute("type", "radio");
      inputRadio.setAttribute("id", element);
      inputRadio.setAttribute("name", "optSelect");
    }

    objFinal.appendChild(frag);
  }

  // Métodos Públicos
  heliosSelect.prototype.mount = function() {
    // Build out our Modal
    buildSelect.call(this);
  };

  // Utility method to extend defaults with user options
  function extendDefaults(source, properties) {
    var property;
    for (property in properties) {
      if (properties.hasOwnProperty(property)) {
        source[property] = properties[property];
      }
    }
    return source;
  }
})();

$(document).ready(function () {
        var lista = [];
        fetch('https://swapi.co/api/people')
            .then(response => response.json()) // retorna uma promise
            .then(result => {
                var dados = result.results;
                var arrayDados = [];
                for (i in dados) {
                    arrayDados.push(dados[i].name);
                }
                var lista = arrayDados.slice();
                $('#mySelect2').customSelect({
                    border: '1px solid #cecece',
                    defaultText: 'Escolha uma opção',
                    list: lista,
                    icon: '❤'
                });
            })
            .catch(err => {
                // trata se alguma das promises falhar
                console.error('Failed retrieving information', err);
            });
        $('#mySelect').customSelect({
            border: '1px solid #cecece',
            defaultText: 'Escolha uma opção',
            list: ['Opção 1', 'Opção 2'],
            icon: '❤'
        });
    });

 var lista = ['1', '2', '3'];
    var mySelect = new heliosSelect('#mySelectVanilla', {
        items: lista,
    });
    mySelect.mount();
              
            
!
999px

Console