Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">
<main>
        <h1>Simple example</h1>
        <div id="mySelect"></div>
    </main>
            
          
!
            
                * {
            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);
}
            
          
!
            
              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
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console