css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

            
              <html lang="en">
<head>
  <meta charset="UTF-8">
  <title>DP</title>
  <style>
    body {
      width: 100%;
      height: 100%;
    }
    .test-tank {
      width: 450px;
      margin: 50px auto;
    }
    .demo-box {
      width: 150px;
    }
    .margin-top-50 {
      margin-top: 50px;
    }
  </style>
</head>
<body>
<a href="https://github.com/gucheen"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
<div class="test-tank">
  <h1>GPDP Dropdown Selector</h1>
  <h2>Google plus like dropdown selector</h2>
  <p>pure JavaScript</p>
  <div class="demo-box margin-top-50">
    <div class="dp-container" data-key="" data-value="">
      <div class="dp-unit">
        <div class="dp-span">Year</div>
        <ul class="dp-menu">
          <li class="dp-item" data-value="2013">2013</li>
          <li class="dp-item" data-value="2014">2014</li>
          <li class="dp-item" data-value="2015">2015</li>
        </ul>
      </div>
    </div>
    <div class="margin-top-50">result: <span class="test-result"></span></div>
  </div>
  <div class="margin-top-50">
    <div class="demo-box test2"></div>
    <div class="margin-top-50">result: <span class="test2-result"></span></div>
  </div>
  <p class="margin-top-50">Written by <a href="http://guchengf.me">Guc</a></p>
</div>
</body>
</html>
            
          
!
            
              $color-text: #404040;
$color-white: #fff;
$border-radius-span: 2px;
$border-radius-menu: 3px;

@mixin background-gradient {
  background-image: -webkit-linear-gradient(top, transparent, transparent);
  background-image: linear-gradient(top, transparent, transparent);
}

.dp-container {
  @include background-gradient;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  .dp-unit {
    .dp-span {
      box-sizing: border-box;
      -webkit-border-radius: $border-radius-span;
      border-radius: $border-radius-span;
      background-color: $color-white;
      border: 1px solid #d9d9d9;
      color: $color-text;
      cursor: default;
      font-size: 12px;
      font-weight: bold;
      line-height: 27px;
      list-style: none;
      margin: 0 2px;
      min-width: 46px;
      outline: none;
      padding: 0 18px 0 6px;
      text-align: center;
      text-decoration: none;
      &:hover {
        background-color: $color-white;
        @include background-gradient;
        -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .1);
        box-shadow: 0 1px 1px rgba(0, 0, 0, .1);
        border-color: #b8b8b8;
        color: $color-text;
      }
    }
    .dp-menu {
      box-sizing: border-box;
      -webkit-border-radius: $border-radius-menu;
      border-radius: $border-radius-menu;
      -webkit-box-shadow: 0 2px 40px rgba(0, 0, 0, .4);
      box-shadow: 0 2px 40px rgba(0, 0, 0, .4);
      -webkit-transition: opacity .218s;
      transition: opacity .218s;
      background: $color-white;
      border: 1px solid #ccc;
      border: 1px solid rgba(0, 0, 0, .2);
      cursor: default;
      font-size: 13px;
      margin: 0;
      outline: none;
      padding: 6px 0;
      position: absolute;
      display: none;
      &.open {
        display: block;
      }
      .dp-item {
        box-sizing: border-box;
        position: relative;
        color: #333;
        cursor: pointer;
        list-style: none;
        margin: 0;
        padding: 6px 8em 6px 30px;
        white-space: nowrap;
        &:hover {
          background-color: #f5f5f5;
          border-color: #eee;
          border-style: dotted;
          border-width: 1px 0;
          padding-top: 5px;
          padding-bottom: 5px;
        }
      }
    }
  }
}
            
          
!
            
              "use strict";

/**
 * GPDP dropdown selector
 * Constructor for building object
 * @param element
 * @param {Object=} options
 * @param {Array.<Object>=} options.data
 * @param {boolean} [options.valueReturnByFunction=true]
 * @param {string} options.name
 * @returns {DP}
 * @constructor
 */
var DP = function (element, options) {
  var self = this;

  // private data tank
  self.store = {};

  // private settings
  self.settings = {};

  // store container
  self.container = element;
  if (typeof options === 'undefined' || typeof options.data === 'undefined') {
    // DOM already
    // store all elements
    self.unit = self.container.getElementsByClassName('dp-unit')[0];
    self.span = self.container.getElementsByClassName('dp-span')[0];
    self.menu = self.container.getElementsByClassName('dp-menu')[0];
  } else {
    // automatically getting return value of function types data
    self.settings.valueReturnByFunction = options.valueReturnByFunction || true;

    // create all elements from data of options
    // store data
    self.data = options.data;

    // validate if data's type is Array
    if (Array.isArray(self.data)) {
      // empty current container (if any)
      self.container.innerHTML = '';
      self.container.classList.add('dp-container');

      // create all elements
      // unit
      self.unit = document.createElement('div');
      self.unit.classList.add('dp-unit');
      self.container.appendChild(self.unit);

      // span(label)
      self.span = document.createElement('div');
      self.span.classList.add('dp-span');
      self.span.textContent = options.name;
      self.unit.appendChild(self.span);

      // menu(ul)
      self.menu = document.createElement('ul');
      self.menu.classList.add('dp-menu');
      self.unit.appendChild(self.menu);

      // insert menu list
      var listElement;

      self.data.map(function (element, index) {
        listElement = document.createElement('li');
        listElement.classList.add('dp-item');
        listElement.textContent = element.label;
        listElement.dataset.index = index;
        self.menu.appendChild(listElement);
      });
    } else {
      console.error('Unsupported data type');
    }
  }

  /* bind click event */
  document.addEventListener('click', function (event) {
    if (self.menu.classList.contains('open') && !self.isDescendant(self.container, event.target)) {
      self.menu.classList.remove('open');
    }
  });

  // click on tag
  self.span.addEventListener('click', function () {
    self.menu.classList.toggle('open');
  });

  // click on menu
  self.menu.addEventListener('click', function (event) {
    if (event.target.classList.contains('dp-item')) {
      var index = parseInt(event.target.dataset.index, 10);

      if (index > -1) {
        self.setValueIndex(index);
      } else {
        self.setValue(event.target.dataset.value);
      }
      self.close();
    }
  });

  return this;
};

/**
 * Attach an event
 * @param event - event's name
 * @param {eventCallback}func - callback function
 */
DP.prototype.listen = function (event, func) {
  this._events = this._events || {};
  this._events[event] = this._events[event] || [];
  this._events[event].push(func);
};

/**
 * callback function definition of events
 * @callback eventCallback
 * @param {*} value - current selected value
 */

/**
 * Detach an event
 * @param event - event's name
 * @param func - callback function
 */
DP.prototype.unlisten = function (event, func) {
  this._events = this._events || {};
  if( event in this._events === false  )	return;
  this._events[event].splice(this._events[event].indexOf(func), 1);
};

/**
 * Trigger an event
 * @private
 * @param event - event's name
 */
DP.prototype.trigger = function (event) {
  this._events = this._events || {};
  if (event in this._events === false) return;
  for (var i = 0; i < this._events[event].length; i++) {
    this._events[event][i].apply(this, [this.getValue(), Array.prototype.slice.call(arguments, 1)]);
  }
};

/**
 * get current selected value
 * @returns {*} - current value
 */
DP.prototype.getValue = function () {
  var value;
  var index;

  index = parseInt(this.store.currentIndex, 10);
  if (index > -1) {
    value = this.data[index].value;
    if (typeof value === 'function') {
      value = value();
    }
  } else {
    value = this.store.value;
  }
  return value;
};

/**
 * set current selected value
 * @param value
 */
DP.prototype.setValue = function (value) {
  this.store.currentIndex = null;
  this.store.value = value;
  this.trigger('changeValue');
  return true;
};

/**
 * set current selected value(index mode)
 * @private
 * @param index
 */
DP.prototype.setValueIndex = function (index) {
  this.store.value = null;
  this.store.currentIndex = index;
  this.trigger('changeValue');
};

/**
 * open dropdown menu
 */
DP.prototype.open = function () {
  this.menu.classList.add('open');
};

/**
 * close dropdown menu
 */
DP.prototype.close = function () {
  this.menu.classList.remove('open');
};

//region Function for checking descendant
/**
 * Check descendant
 * @private
 * @param parent - parent element
 * @param child - child element
 * @returns {boolean} - if is descendant
 */
DP.prototype.isDescendant = function (parent, child) {
  var node = child.parentNode;
  while (node != null) {
    if (node == parent) {
      return true;
    }
    node = node.parentNode;
  }
  return false;
};
//endregion

var testDp = new DP(document.getElementsByClassName('dp-container')[0]);

testDp.listen('changeValue', function (value) {
  document.getElementsByClassName('test-result')[0].textContent = value;
});

var testDp2 = new DP(document.getElementsByClassName('test2')[0], {
  name: 'Complex data',
  data: [
    {label: 'Object', value: {a: 1}},
    {label: 'Array', value: [1, 2]},
    {
      label: 'Function',
      value: function () {
        return 'value returned by function';
      }
    },
    {label: 'Null', value: null}
  ]
});

testDp2.listen('changeValue', function (value) {
  console.log('%cLOG VALUE: testDp2', 'color: blue', value);
  document.getElementsByClassName('test2-result')[0].textContent = (typeof value) + ' : ' + JSON.stringify(value, null, 2);
});
            
          
!
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.
Loading ..................

Console